元素内容居中
元素内容居中,如文字,可以设置水平居中和行高与容器的高度一致
text-align: center;/* 水平居中 */
line-height: 200px;/* 行高与容器一致 */
元素居中
两个盒子嵌套,使最里面盒子居中。
<div id="box1">
<div id="box2"></div>
</div>
方法一:固定定位,需要固定元素大小。
用left和top将右上角定位到父元素中心,再用margin调节,也可以直接使用calc直接定位到中心
#box1{
width: 400px;height: 400px;/* 父容器宽高 */
border: 1px red solid;/* 边框 */
position: relative;/* 相对定位 */
}
#box2{
width: 100px;height: 100px;/* 子元素 */宽高 */
background-color: teal;/* 背景颜色 */
position: absolute;/* 绝对定位 */
left: calc(50% - 50px);top: calc(50% - 50px);}/* 相较于父元素位置 */
方法二:利用位移
同样使用了固定定位,再用transform: translate以自身为基准位移,适合box大小不固定
#box1{
width: 400px;height: 400px;
border: 1px red solid;
position: relative;
}
#box2{
width: 100px;height: 100px;
background-color: teal;
position: absolute;
left: 50%;top: 50%;
transform: translate(-50%,-50%);/* 向右边和上边位移自身的一半 */
}
方法三:上下左右全0使margin:auto生效
固定定位会使元素脱离文档流,当四个方向距离都为0时,margin:auto;会生效,从而达到居中的目的。auto:自适应。
#box1{
width: 400px;height: 400px;
border: 1px red solid;
position: relative;
}
#box2{
width: 100px;height: 100px;
background-color: teal;
position: absolute;
left: 0;right: 0;top: 0; bottom: 0;/* 四边全0 */
margin: auto;/* 自适应 */
}
方法四:使用弹性布局
弹性盒子在一维布局中很方便,是比较常用的布局方式。可以用margin:auto;和justify-content: center;align-items: center;两种方式实现。
#box1{
width: 400px;height: 400px;
border: 1px red solid;
display: flex;
}
#box2{
width: 100px;height: 100px;
background-color: teal;
/* margin: auto; */ /* 自适应 */
justify-content: center;/* 水平居中 */
align-items: center;/* 垂直居中 */
}