方式一:知道元素高度
- 给该元素设置绝对定位;
- 设置绝对定位元素的
left:50%;
,top:50%;
- 再设置绝对定位元素的
margin-left: -元素宽度的一半px;
,margin-top: -元素高度的一半px;
- 注意:如果只需要水平居中,只需要设置
left
和margin-left
的值;
如果只需要垂直居中,只需要设置top
和margin-top
的值; - 弊端:需要确切知道元素的宽度,只能为某一张图片设置,图片替换掉后,就不一定有效。
<div class="box1">
<div class="box2"></div>
</div>
<style>
.box2{
background: #33AE75;
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>
方式二:不知道元素的高度
- 给该元素设置绝对定位;
- 给该元素设置
margin: auto;
- left、top、bottom、right的值都为0。
<div class="box1">
<div class="box2"></div>
</div>
<style>
.box2{
width: 200px;
height: 200px;
background: #b92c28;
margin: auto;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
}
</style>
方式三:CSS3的相关属性
- 给该元素设置绝对定位;
- 设置
top: 50%;
,left: 50%;
- 设置
transform: translate(-50%,-50%);
<div class="box1">
<div class="box2"></div>
</div>
<style>
.box2{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 200px;
background: #8d66c6;
}
</style>
水平居中:
left:50%;
transform: translateX(-50%);
垂直居中:
top:50%;
transform: translateY(-50%);
水平垂直居中:
left:50%;
top:50%;
transform: translate(-50%, -50%);
方式四:flex布局
- 设置容器为伸缩布局,并设置高度和宽度;
- 设置伸缩容器主轴对齐方式和侧轴对齐方式为
center
<div class="box1">
<div class="box2"></div>
</div>
<style>
html,body{
width: 100%;
height: 100%;
}
.box1{
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.box2{
width: 100px;
height: 100px;
background: #000;
}
</style>
垂直水平居中图片
- 给容器设置以下代码:
//display: table-cell;
//vertical-align: middle;
//text-align: center;
<div class="box1">
<img src="./../images/1.jpg" alt="">
</div>
<style>
.box1{
width: 500px;
height: 500px;
display: table-cell;
vertical-align: middle;
text-align: center;
border: 1px solid #000;
}
.box1 img{
width: 100px;
height: 100px;
background: #000;
}
</style>
水平居中图片
- 需要配合
text-align: center;
使用,其父元素需要设置text-align: center;
- 给图片设置
margin: 0 -100%;
<div class="box1">
<img src="./../images/1.jpg" alt="">
</div>
<style>
.box1{
width: 400px;
height: 400px;
border: 10px solid red;
margin: 50px auto;
text-align: center;
}
.box1 img{
margin: 0 -100%;
}
</style>