123456789101112131415161718192021222324252627282930313233343536 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>使用绝对定位和负外边距进行垂直居中</title>
- <style>
- #box {
- width: 300px;
- height: 300px;
- background: #ddd;
- position: relative;
- }
- #child {
- width: 50%;
- height: 30%;
- background: orange;
- position: absolute;
- top: 50%;
- margin: -15% 0 0 0;
- }
- </style>
- </head>
- <body>
- <h1>使用绝对定位和负外边距进行垂直居中</h1>
- <p>这种方式的原理实质上和前两种相同。补充的一点是:margin 的取值也可以是百分比,这时这个值规定了该元素基于父元素尺寸的百分比,可以根据实际的使用场景来决定是用具体的数值还是用百分比。</p>
- <div id="box">
- <div id="child">test vertical align</div>
- </div>
- </body>
- </html>
|