css垂直居中
kingcwt2020-11-22前端css
一 、flex实现垂直居中
<template>
<div id="app">
<div class="box">
<div class="children-box"></div>
</div>
</div>
</template>
<style type="text/css">
.box {
width: 200px;
height: 200px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.children-box {
background: yellow;
height: 100px;
width: 100px;
}
</style>
二 、grid布局
<template>
<div id="app">
<div class="box">
<div class="children-box"></div>
</div>
</div>
</template>
<style type="text/css">
.box {
width: 200px;
height: 200px;
border: 1px solid red;
display: grid;
}
.children-box {
width: 100px;
height: 100px;
background: yellow;
margin: auto;
}
</style>
三 、绝对定位 + left/right/bottom/top + margin
<template>
<div id="app">
<div class="box">
<div class="children-box"></div>
</div>
</div>
</template>
<style type="text/css">
.box {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.children-box {
position: absolute;
display: inline;
top: 0;
left: 0;
right: 0;
bottom: 0px;
background: yellow;
margin: auto;
height: 100px;
width: 100px;
}
</style>
四 、绝对定位 + transform
<template>
<div id="app">
<div class="box">
<div class="children-box"></div>
</div>
</div>
</template>
<style type="text/css">
.box {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.children-box {
position: absolute;
width: 100px;
height: 100px;
background: yellow;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
五 、绝对定位和负magin值
<template>
<div id="app">
<div class="box">
<div class="children-box"></div>
</div>
</div>
</template>
<style type="text/css">
.box {
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.children-box {
position: absolute;
width: 100px;
height: 100px;
background: yellow;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
参考文章传送门:面试官:你能实现多少种水平垂直居中的布局(定宽高和不定宽高)