一、水平居中
1.1.行内元素:
方法一:
块级父级设置
text-align
行内水平居中方法一:行内元素水平居中,看父级元素是不是块级,如果是块级元素字节text-align即可;
.bigbox{
text-align: center;
width: 900px;
height: 400px;
background-color: antiquewhite;
}
.smallinline{
/*行内元素不可以设置宽和高度,由自己的内容撑开*/
background-color: aqua;
}
<div class="bigbox">
<span class="smallinline">hhh</span>
</div>
1.2.块级元素:
方法一: margin:auto;
两种情况:
①设置宽度:margin :auto
即可;
②没有设置宽度:此时的宽度会和父级元素宽度一致。不存在水平居中问题,如果非要水平居中,那么就display改成inline,然后给父级元素设置text-align:center
方法二:使用定位属性(分定不定宽两种情况)
首先设置父元素为相对定位,再设置子元素为绝对定位,设置子元素的left:50%,即让子元素的左上角水平居中; 两种方法:
①定宽度:父级相对定位和子元素绝对定位的前提下,对子元素设置margin-left:
元素宽度的一半px;
或者设置transform: translateX(-50%);
②不定宽度:父级相对定位和子元素绝对定位的前提下, 对子元素设置transform: translateX(-50%);
方法三: 使用flex布局——宽度定不定都可以使用flexbox布局,只需要给待处理的块状元素的父元素添加属性 display: flex; justify-content: center;
使用flexbox布局,只需要给待处理的块状元素的父元素添加属性
display: flex; justify-content: center;
.bigbox3{
display: flex;/*开启弹性盒模型*/
justify-content: center;/*主轴的一种布局所有的主轴(元素排列方向)的元素在中间居中*/
width: 500px;
height: 300px;
background-color: black;
}
.smallbox3{
width: 300px;
height: 300px;
background-color: white;
}
<div class="bigbox3">
<div class="smallbox3">
我是块级元素水平居中方法三:弹性盒模型
</div>
<div>
二,水平垂直居中
方法一:定位 + margin
使用绝对定位,四个方向的偏移量全都为 0,同时设置
margin:auto
分配剩余空间,令元素 的均匀拖拽至父元素的中心位置。
例如:
.box-container{
position: relative;
}
.box {
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
方法二:设置父元素为相对定位,给子元素设置绝对定位
(1)left: 50%; top: 50%; margin-left: -元素宽度的一半px;
margin-top:-元素高度的一半px;
(2)left: 50%; top: 50%; transform:
translateX(-50%) translateY(-50%);也ok
方法三:使用flex布局实现——设置父元素为flex定位
设置父元素为flex定位,justify-content: center; align-items: center;
BigBox{
display: flex;
justify-content: center;
align-items: center;
width: 800px;
height: 500px;
background-color: #acaadd;
}
.SmallBox{
background-color: antiquewhite;
}
<div class="BigBox">
<div class="SmallBox">
我是水平垂直居中不定宽高的方法三
</div>
</div>