在面试时经常会问到css布局的问题,尤其是居中问题,于是把想到的方法做以下总结。如有补充,欢迎私聊哦~
一、块级元素
1、flex方法
HTML文件
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
CSS文件
.father {
background-color: yellow;
width: 500px; /*此处未知,方面展示所以假设了宽高*/
height: 300px; /*此处未知,方面展示所以假设了宽高*/
display: flex;
justify-content: center; /*垂直居中*/
align-items: center; /*水平居中*/
}
.child {
width: 200px; /*此处未知,方面展示所以假设了宽高*/
height: 100px; /*此处未知,方面展示所以假设了宽高*/
background-color: thistle;
}
2、使用css3 的translate+absolute
HTML文件
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
CSS文件
.father {
background-color: yellow;
width: 500px;
height: 300px;
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
background-color: thistle;
}
3、 使用absolute + margin
.father {
border: 10px solid red;
height: 400px;
position: relative;
}
.child {
position: absolute;
width: 200px;
height: 200px;
background-color: gray;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
二、行内元素
水平居中:
1.首先看它的父元素是不是块级元素,如果是,则直接给父元素设置 text-align: center;
2.如果不是,则先将其父元素设置为块级元素,再给父元素设置 text-align: center;
垂直居中:
1.只需要设置行内元素的"行高line-height等于盒子的高"即可,仅适用于纯文字;
2.父元素设置成table-cell表格形式,使用vertical-align: middle即可使内联元素垂直居中;