Day14:CSS vertical center

verticle-align:middle

Vertical align: middle is a common method to realize the vertical center of css. However, it should be noted that the precondition for the effectiveness of vertical is diaplay: inline block.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css horizontally</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 implementation

display:flex implements the vertical center of css by giving the parent element display:flex, and the child element align self: Center.

<style>
#out{
background: blue;
width: 600px;
height: 300px;
display: flex;
}
#in {
background: yellow;
width: 50%;
height: 50%;
align-self: center;
}
//Parent element display:flex
//Child element align self: Center

Pseudo element: before to realize CSS vertical center

<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 to realize css vertical center

Give the parent element display:table, and the child element display:table cell to realize the vertical center of 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>

Hidden node to realize CSS vertical center

<style>
#out{
background: blue;
width: 600px;
height: 300px;
}
#hide{
width: 50%;
 height: 25%;
}
//The height of the hidden node is half of the remaining height
#in {
background: yellow;
width: 50%;
height: 50%;
}
</style>
<body id="out">
<div id="hide"></div>
<div id="in"></div>
</body>

CSS vertical center through transform

<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 to realize CSS vertical center

<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>

Please praise! Because your encouragement is the biggest driving force of my writing!

Official wechat public account

Forced communication group: 711613774

Push communication group

Posted by dape2009 on Fri, 25 Oct 2019 13:14:37 -0700