Day14:CSS垂直居中

verticle-align:middle

vertical-align:middle实现css垂直居中是常用的方法,但是需要注意,vertical生效的前提是diaplay:inline-block

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css水平居中</title>
<style>
#out {
 background: blue;
 width: 600px;
 height: 300px;
}
#in {
 background: yellow;
 width: 50%;
 height: 50%;
 display: inline-block;
 vertical-align: middle;
}
</style>
</head>
<body>
<div id="out">
 <div id="in"></div>
 </div>
</body>
</html>

display: flex实现

display:flex实现css垂直居中的方法是给父元素display: flex;而子元素align-self:center;

<style>
#out{
background: blue;
width: 600px;
height: 300px;
display: flex;
}
#in {
background: yellow;
width: 50%;
height: 50%;
align-self: center;
}
父元素display:flex
子元素align-self:center

伪元素:before实现CSS垂直居中

<style>
#out{
background:blue;
width: 600px;
height: 300px;
display: block;
}
#out:before{
content: '';
display:inline-block;
vertical-align:middle;
height:100%;
}
#in{
background: yellow;
width: 50%;
height: 50%;
display: inline-block;
vertical-align: middle;
}
</style>

display:table-cell实现css垂直居中

给父元素display:table,子元素display: table-cell的方式实现css垂直居中。

<style>
#out {
background: blue;
width: 600px;
height: 300px;
dispaly: table;
}
#in{
background: yellow;
width: 50%;
height: 50%;
display:table-cell;
vertical-align:middle;
}
</style>

隐藏节点实现CSS垂直居中

<style>
#out{
background: blue;
width: 600px;
height: 300px;
}
#hide{
width: 50%;
 height: 25%;
}
隐藏节点的height为剩余高度的一半
#in {
background: yellow;
width: 50%;
height: 50%;
}
</style>
<body id="out">
<div id="hide"></div>
<div id="in"></div>
</body>

通过transform实现CSS垂直居中

<style>
#out {
background: blue;
width: 600px;
height: 300px;
}
#in{
background: yellow;
width: 50%;
height: 50%;
position: relative;
top: 50%;
transform: translateY(--50%);
}
</style>

line-height实现CSS垂直居中

<style>
#out {
background: blue;
width: 600px;
height: 300px;
}
#in {
 width: 50%;
 height: 50%;
 line-height: 300px;
}
</style>

<body>
<div id="out">
 <p id="in">css</p>
</div>
</body>

请点赞!因为你的鼓励是我写作的最大动力!

官方微信公众号

吹逼交流群:711613774

吹逼交流群

posted @ 2019-07-14 22:24  达达前端  阅读(98)  评论(0编辑  收藏  举报