一、实现水平垂直居中最便捷的方法
HTML:
<div class="container">
<div class="box"></div>
</div>
CSS:
.container {
width: 100px;
height: 100px;
background: #eee;
display: flex;
// display: grid;
// display: inline-flex;
// display: inline-grid;
}
.box {
width: 60px;
height: 60px;
background: #000;
margin: auto;
}
二、通过 Flex 的两个属性实现
.container {
width: 100px;
height: 100px;
background: #eee;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 40px;
height: 40px;
background: #000;
}
三、通过 position 和 transform
在不知道本元素宽高情况下,即可实现水平垂直居中。
.container {
width: 100px;
height: 100px;
background: rgb(175, 203, 175);
position: relative;
}
.box {
width: 40px;
height: 40px;
background: #000;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
四、通过 position 和 margin
此方法需要知道本元素宽高。
.container {
width: 100px;
height: 100px;
background: #eee;
position: relative;
}
.box {
width: 40px;
height: 40px;
background: #000;
position: absolute;
top: 50%;
left: 50%;
margin-left: -20px;
margin-top: -20px;
}
五、让绝对定位的元素水平垂直居中
如下,想让 一个元素对其父元素的父元素定位,且需要位置处于水平垂直居中。就可以用上文的 三、四 方法。也可以用下面方法:(推荐用 三、position 和 transform)
<style>
.container {
width: 500px;
height: 300px;
position: relative;
background-color: rgb(208, 168, 58);
}
.box1 {
width: 50px;
height: 120px;
background-color: rgb(204, 245, 165);
}
.box2 {
width: 50px;
height: 120px;
background-color: rgb(188, 138, 238);
}
.block {
position: absolute;
width: 100px;
height: 100px;
background-color: rgb(118, 229, 166);
margin: auto; /*水平垂直居中*/
/* margin: 0 auto; *//*水平居中*/
/* margin: auto 0; *//*垂直居中*/
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div class="container ">container
<div class="box1">box1</div>
<div class="box2">box2
<div class="block">block</div>
</div>
</div>
行内元素水平垂直居中最便捷方式
垂直居中:height
和 line-height
值相等。
水平居中:text-align: center
<style>
div {
width: 100px;
height: 100px;
background-color: red;
line-height: 100px;
text-align: center;
}
span {
background-color: blue;
}
</style>
</head>
<body>
<div>
<span>111</span>
</div>