你能够想到多少种CSS中让元素居中的方法?
行内元素水平居中
给其父元素设置text-align: center
即可
.box {
text-align: center;
}
行内元素水平居中
给元素本身添加margin-left: auto; margin-right: auto;
.box {
width: 600px;
margin-left: auto;
margin-right: auto;
}
padding垂直居中
在容器高度不固定的情况下,给内容设置相同的上下padding,使内容撑开父容器,达到视觉上垂直居中的效果。
绝对定位居中
.box-parent {
width: 600px;
height: 600px;
background-color: black;
position: relative;
}
.box {
width: 300px;
height: 300px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -150px;
}
<div class="box-parent">
<div class="box"></div>
</div>
因为给left
和right
属性设置百分比值时是相对父容器的长度,所以当设置了 left: 50%; right:50%;
之后,元素的左上角会在父容器的中心。此时如果想要使元素整体位于父容器的中心,需要使元素在其原始位置向左和上移动本身长度和高度的一半。
/*上述便是为何要加下面两句负margin的理由*/
margin-top: -150px;
margin-left: -150px;
/*亦或是采用如下写法,效果相同*/
top: calc(50% - 150px);
left: calc(50% - 150px);
宽高的不固定的情况
上述情况用于元素自身宽高是固定的情况,当宽高不固定时,我们就无从知晓元素该偏移多少距离。
此时可以使用下面的写法:
.box {
width: 300px;
height: 300px;
position: absolute;
top: 50%;
left:50%;
transform: translate(-50%,-50%);
}
/*第一个参数表示x轴移动距离,第二个参数代表y轴移动距离*/
transform: translate(20px, 20px);
transform: translate(10%, 10%); /*当采用百分比写法时,移动距离是相对自身的宽高,例如此处是本身宽高的10%*/
注意点:transform属性只对块级元素生效。
vertical-align: middle;垂直居中
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 500px;
height: 300px;
outline: 1px solid red;
margin: 10px auto;
}
.box h1 {
vertical-align: middle;
display: inline-block;
}
.box::before {
content: "1";
height: 100%;
display: inline-block;
background-color: pink;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="box">
<h1>用于垂直居中显示的文本</h1>
</div>
</body>
核心就是使用vertical-align: middle;
flex布局居中
.flex-box {
width: 100vw;
height: 100vh;
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
可实现.flex-box
子元素的居中
如有错误,还望指出