让div在父元素中垂直居中
1.利用定位和margin:auto让子元素在父元素中水平垂直居中
<style>
.box {
width: 500px;
height: 500px;
margin: 100px auto;
border: 1px solid #f00;
position: relative;
}
.box1 {
width: 100px;
height: 100px;
background-color: #0f0;
position: absolute;
left: 0;
bottom: 0;
top: 0;
right: 0;
margin: auto;
}
</style>
<div class="box">
<div class="box1"></div>
</div>
实现效果:
2.利用定位以及transform和margin取值属性让其居中
利用定位margin取值让子元素居中:
<style>
.box {
width: 500px;
height: 500px;
margin: 100px auto;
border: 1px solid #f00;
position: relative;
}
.box1 {
width: 100px;
height: 100px;
background-color: #ff0;
position: absolute;
left:50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
<div class="box">
<div class="box1"></div>
</div>
margin取值应为子元素宽高的一半(margin的取值可以为负值,但padding显然不行),缺点是必须知道子元素的宽高具体大小且需要计算,当子元素的大小被修改后对应的margin值也需要修改否则达不到剧中的效果,从而引导我们使用更方便快捷的方法。
利用定位与transform实现垂直水平居中:
<style>
.box {
width: 500px;
height: 500px;
margin: 100px auto;
border: 1px solid #f00;
position: relative;
}
.box1 {
width: 100px;
height: 100px;
background-color: #ff0;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="box">
<div class="box1"></div>
</div>
transform:translate(-50%,-50%)
第一个-50%是指x轴方向向左位移子元素本身宽的百分之50,而第二个-50%是指元素在y轴方向向上平移子元素本身高的百分之50。
二者的原理是相同的都是在加了left:50%
与top:50%
后再减去盒子宽高的一半来实现水平垂直居中。
3.弹性盒display:flex;
<style>
.box {
width: 500px;
height: 500px;
margin: 100px auto;
border: 1px solid #f00;
display: flex;
justify-content: center;
align-items: center;
}
.box1 {
width: 100px;
height: 100px;
background-color: #ff0;
}
</style>
<div class="box">
<div class="box1"></div>
</div>
给父元素添加display:flex;让它变成弹性盒,在利用justify-content: center;与 align-items: center;,让子元素在主轴与交叉轴(纵轴)方向居中。缺点是在网页端弹性盒因为兼容问题一般不被经常使用。
4.子元素转为行内块元素
<style>
.box {
width: 500px;
height: 500px;
margin: 100px auto;
border: 1px solid #f00;
text-align: center;
}
.box1 {
width: 100px;
height: 100px;
background-color: #ff0;
display: inline-block;
vertical-align: middle;
}
span {
height: 100%;
width: 0;
vertical-align: middle;
display: inline-block;
}
</style>
<div class="box">
<div class="box1"></div><span></span>
</div>
设置一个元素在一个容器中垂直居中,必须更改默认的display
属性值为inline-block;
并加上同级元素(标尺)(同级元素[标尺]样式设置为vertical-align:middle;width:0;height:100%;display:inline-block;
)
三个条件:
1:必须给容器(父元素)加上text-align:center;
2:必须给当前元素转成行内块元素(display:inline-block;)再给当前元素加上vertical-align:middle;
3:在当前元素的后面(没有回车)加上同级元素span;并对span进行
vertical-align:middle;
width:0;
height:100%;
display:inline-block
5.父元素转为gird利用网格布局
<style>
.box {
width: 400px;
height: 400px;
border: 1px solid red;
margin: 100px auto;
display: grid;
/* 第一个数值为垂直方向对齐方式 第二数值为水平方向对齐方式 */
place-items: center center;
}
.box1 {
width: 100px;
height: 100px;
background-color: #00f;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
原理类似于利用弹性布局,将父元素转换为网格元素再利用ustify-items:center
(内容在单元格内的水平对齐方式),和align-items:center;
(内容在单元格内垂直对齐方式)place-items
为复合写法,相当于父元素为一个一行一列的单元格而box1为它单元格中的元素。(其实很利用place-content
也能做到原理还没搞懂...)