可以说这是前端面试必考题了,很基础,很重要!!!
test盒在app盒中垂直居中
方法一:
父元素position:relative,子元素position:absolute,利用margin:0,自动垂直居中
<style type="text/css">
.app{
width: 300px;
height: 300px;
background: lightsalmon;
position: relative;
}
.test{
background: lightskyblue;
width: 100px;
height: 100px;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto;
}
</style>
<body>
<div class="app">
<div class="test">test</div>
</div>
</body>
方法二:
利用flex布局,align-items、justify-content属性
<style type="text/css">
.app{
width: 300px;
height: 300px;
background: lightsalmon;
display: flex;
align-items: center;
justify-content: center;
}
.test{
background: lightskyblue;
width: 100px;
height: 100px;
}
</style>
<div class="app">
<div class="test">test</div>
</div>
方法三:
利用绝对定位和负边距
<style type="text/css">
.app{
width: 300px;
height: 300px;
background: lightsalmon;
position: relative;
}
.test{
background: lightskyblue;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
<div class="app">
<div class="test">test</div>
</div>
方法四:
利用transform属性
<style type="text/css">
.app{
width: 300px;
height: 300px;
background: lightsalmon;
position: relative;
}
.test{
background: lightskyblue;
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
<div class="app">
<div class="test">test</div>
</div>
方法五:(不推荐)
利用table-cell,此时test盒会完全填充app盒,且padding、margin会失效
<style type="text/css">
.app{
width: 300px;
height: 300px;
background: lightsalmon;
display: table;
}
.test{
background: lightskyblue;
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
<div class="app">
<div class="test">test</div>
</div>