水平垂直居中你不知的那些套路
2023-10-01 01:54:11
正文
一、定宽盒子水平居中
1. 利用 margin:0 auto;
.box {
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
}
解析:
margin: 0 auto;
属性可以将元素水平居中。因为它的原理是给元素左右两侧都留出相同大小的空白区域,使得元素在水平方向上居中。如果想要水平居中一个块级元素,只需要设置它的左右margin
属性为auto
即可。
2. 利用 text-align: center;
.box {
width: 200px;
height: 200px;
background-color: red;
text-align: center;
}
解析:
text-align: center;
属性可以将元素内的文本水平居中。但是,它不能将元素本身水平居中。所以,如果想要水平居中一个块级元素,还需要额外设置它的左右margin
属性为auto
。
3. 利用 flexbox
.container {
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 200px;
height: 200px;
background-color: red;
}
解析:
利用flexbox布局可以轻松实现元素的水平垂直居中。justify-content: center;
属性可以将元素在水平方向上居中,align-items: center;
属性可以将元素在垂直方向上居中。
二、不定宽盒子水平居中
1. 利用绝对定位
.container {
position: relative;
}
.box {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
width: 200px;
height: 200px;
background-color: red;
}
解析:
利用绝对定位可以将元素从文档流中脱离出来,并将其定位在指定的位置。left: 50%;
属性将元素水平定位在父元素的中间位置,transform: translate(-50%, 0);
属性将元素向左平移50%,使得元素的中心点与父元素的中心点重合。
2. 利用 flexbox
.container {
display: flex;
justify-content: center;
}
.box {
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
}
解析:
利用flexbox布局也可以实现不定宽盒子的水平居中。justify-content: center;
属性可以将元素在水平方向上居中,margin: 0 auto;
属性可以将元素在垂直方向上居中。
3. 利用百分比
.container {
width: 100%;
}
.box {
width: 50%;
height: 200px;
background-color: red;
margin: 0 auto;
}
解析:
利用百分比也可以实现不定宽盒子的水平居中。width: 50%;
属性将元素的宽度设置为父元素宽度的50%,margin: 0 auto;
属性可以将元素在垂直方向上居中。
三、盒子垂直居中
1. 利用绝对定位
.container {
position: relative;
}
.box {
position: absolute;
top: 50%;
transform: translate(0, -50%);
width: 200px;
height: 200px;
background-color: red;
}
解析:
利用绝对定位可以将元素从文档流中脱离出来,并将其定位在指定的位置。top: 50%;
属性将元素垂直定位在父元素的中间位置,transform: translate(0, -50%);
属性将元素向上平移50%,使得元素的中心点与父元素的中心点重合。
2. 利用 flexbox
.container {
display: flex;
align-items: center;
}
.box {
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
}
解析:
利用flexbox布局也可以实现盒子的垂直居中。align-items: center;
属性可以将元素在垂直方向上居中,margin: 0 auto;
属性可以将元素在水平方向上居中。
3. 利用 margin: 0 auto;
.container {
text-align: center;
}
.box {
display: inline-block;
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
}
解析:
利用text-align: center;
属性可以将元素在水平方向上居中,margin: 0 auto;
属性可以将元素在垂直方向上居中。但是,这种方法只适用于行内元素。
四、总结
通过以上几种方法,我们可以轻松实现盒子的水平垂直居中。在实际开发中,我们可以根据具体情况选择合适的方法。
除了以上方法之外,还有一些其他方法可以实现盒子的水平垂直居中,比如利用table
布局、利用grid
布局等等。这些方法各有优缺点,开发者可以根据实际情况选择合适的方法。