CSS垂直居中的方法
- margin auto方法
.div1{
width: 18.75rem;
height:18.75rem;
background: #FFFF00;
position: absolute;
top: 0;
bottom: 0;
margin: auto;
}
2.transform:translateY(100%) 方法
.div1{
width: 18.75rem;
height:18.75rem;
background: #FFFF00;
transform: translateY(100%);
}
#div2{
width: 6.25rem;
height: 6.25rem;
background-color: aqua;
transform: translateY(100%);
}
/-------------------body部分-------------------------/
<body>
<div class="div1">
<div id="div2">
</div>
</div>
</body>
- display:table-cell法
.div1{
width: 18.75rem;
height:18.75rem;
background: #FFFF00;
display: table-cell;
vertical-align: middle;
text-align: center;
}
#div2{
width: 6.25rem;
height: 6.25rem;
background-color: aqua;
vertical-align: middle;
}
<body>
<div class="div1">
<div id="div2">
</div>
</div>
</body>
设置父元素的display:table-cell,并且vertical-align:middle,这样子元素可以实现垂直居中。
4.flex布局法
将父元素设置为display:flex,并且设置align-items:center;
.div1{
width: 18.75rem;
height:18.75rem;
background: #FFFF00;
display: flex;
align-items: center;
}
#div2{
width: 6.25rem;
height: 6.25rem;
background-color: aqua;
}
<body>
<div class="div1">
<div id="div2">
</div>
</div>
</body>