页面中,元素100%高度,垂直居中的问题

这个在实际中很常见,用jquery是很容易实现,用table也很容易实现。其余的方式兼容性其实来都非常差,代码也不易读。

好在有css3,基本上大部分浏览器也支持了。

html和body默认的高度为1行,所以还需要增加,

html,body{
             height:100%;
             margin:0;
            }

justify-content:center;//子元素水平居中
align-items:center;//子元素垂直居中
display:-webkit-flex;

利用css3的flex属性

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
			html,body{
			 height:100%;
			 margin:0;
			}
            #box{
                display:flex;
				height:100%;
                width: 100%;
                /*justify-content属性定义了子项目在主轴上(X轴)的对齐方式。*/
                justify-content: center;
                /*align-items属性定义子项目在交叉轴(Y轴上)上如何对齐。*/
                align-items: center;
            }
            .item{
                width: 50px;
                height: 40px;
                border: 1px solid #00C1B3;
            }
        </style>
    </head>
    <body>
        <div id="box">
            <div class="item">1</div>
            <div class="item">2</div>
            <div class="item">3</div>
            <div class="item">4</div>
            <div class="item">5</div>
        </div>
    </body>
</html>
发布了67 篇原创文章 · 获赞 9 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/robinhunan/article/details/84766779
今日推荐