CSS实现水平居中
- 若是行内元素,则直接给其父元素设置
text-align: center即可 - 若是块级元素,则直接给该元素设置
margin: 0 auto即可 - 若子元素包含浮动元素,则给父元素设置
width:fit-content并且配合margin
.parent {
width: -webkit-fit-content;
width: -moz-fit-content;
width: fit-content;
margin: 0 auto;
}
- 使用flex布局的方式,可以轻松实现水平居中,即使子元素中存在浮动元素也同样适用
// flex 2012年版本写法
.parent {
display: flex;
flex-direction: row;
justify-content: center;
}
- 使用绝对定位的方式,再配合CSS3新增的
transform属性
.child {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
- 使用绝对定位的方式,再配合负值的
margin-left(此方法需要固定宽度)
.child {
position: absolute;
left: 50%;
width: 200px; // 假定宽度为200px
margin-left: -100px; // 负值的绝对值为宽度的一半
}
- 使用绝对定位的方式,再配合
left:0;right:0;margin:0 auto;(此方法需要固定宽度)
.child {
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
width: 200px; // 假定宽度为200px
}
CSS实现垂直居中
- 若元素是单行文本,则直接给该元素设置
line-height等于其父元素的高度 - 若元素是行内块级元素,可以配合使用
display:inline-block;vertical-align:middle和一个伪元素来让内容块居中
.parent::after, .child {
display: inline-block;
vertical-align: middle;
}
.parent::after {
content: "";
height: 100%;
}
- 使用
vertical-align属性并且配合使用display:table和display:table-cell来让内容块居中
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
- 使用flex布局的方式,可以轻松实现垂直居中,即使子元素中存在浮动元素也同样适用
.parent {
display: flex;
align-items: center;
}
- 使用绝对定位的方式,再配合CSS3新增的transform属性
.child {
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
- 使用绝对定位的方式,再配合负值的
margin-top(此方法需要固定高度)
.child {
position: absolute;
top: 50%;
height: 200px; // 假定高度为200px
margin-top: -100px; // 负值的绝对值为高度的一半
}
- 使用绝对定位的方式,再配合
top:0;bottom:0;margin:auto 0;(此方法需要固定高度)
.child {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
height: 200px; // 假定高度为200px
}
CSS实现水平垂直居中
- 使用flex布局的方式同样可以轻松实现水平垂直居中
.parent {
display: flex;
justify-content: center;
align-items: center;
}
- 使用绝对定位的方式,再配合CSS3新增的
transform属性
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
- 使用绝对定位的方式,再配合使用负值的
margin-top和负值的margin-left(此方法需要同时固定宽度和高度)
.child {
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px; // 负值的绝对值为高度的一半
margin-left: -100px; // 负值的绝对值为宽度的一半
width: 200px; // 假定宽度为200px
height: 100px; // 假定高度为100px
}
125jz网原创文章。发布者:江山如画,转载请注明出处:http://www.125jz.com/4449.html
微信扫一扫
支付宝扫一扫