12345678910111213141516171819202122232425262728293031323334353637383940 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>绝对定位结合margin: auto</title>
- <style>
- #box {
- width: 300px;
- height: 300px;
- background: #ddd;
- position: relative;
- }
- #child {
- width: 200px;
- height: 100px;
- background: orange;
- position: absolute;
- top: 0;
- bottom: 0;
- margin: auto;
- line-height: 100px;
- }
- </style>
- </head>
- <body>
- <h1>绝对定位结合margin: auto</h1>
- <p>
- 这种实现方式的两个核心是:把要垂直居中的元素相对于父元素绝对定位,top和bottom设为相等的值,我这里设成了0,当然也可以设为 99999px 或者 -99999px 无论什么,只要两者相等就行,这一步做完之后再将要居中元素的 margin 属性值设为 auto,这样便可以实现垂直居中了。
- 被居中元素的宽高也可以不设置,但不设置的话就必须是图片这种自身就包含尺寸的元素,否则无法实现。
- </p>
- <div id="box">
- <div id="child">test vertical align</div>
- </div>
- </body>
- </html>
|