CSS垂直居中的8种方法

CSS垂直居中的8种方法

  1. 通过verticle-align:middle实现CSS垂直居中。

  2. 通过display:flex实现CSS垂直居中。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Examples</title>
<link href="lianxi2.css" rel="stylesheet">
<style>
    .fa{
    width: 100%;
    background-color: #ccc;
    height: 500px;
    display: flex;
}
.son{
    width: 100px;
    height: 100px;
    background-color: #c60;
    align-self: center;
}
</style>
</head>
<body>
<div class="fa">
    <div class="son"></div>
</div>
</body>
</html>

3.父元素添加伪元素:before实现CSS垂直居中。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Examples</title>
<link href="lianxi2.css" rel="stylesheet">
<style>
    .fa{
    width: 100%;
    background-color: #ccc;
    height: 500px;

    }
    .fa:before{
        display: inline-block;
        vertical-align: middle;
        height: 100%;
        content: " ";
    }
    .son{
    width: 100px;
    height: 100px;
    background-color: #c60;
    display: inline-block;

    }
</style>
</head>
<body>
<div class="fa">
    <div class="son"></div>
</div>
</body>
</html>

4.通过display:table-cell实现CSS垂直居中

5.添加div填充

6.子元素为单行文本是,让子元素line-height等于父元素height。

7.子元素通过transform实现CSS垂直居中。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Examples</title>
<link href="lianxi2.css" rel="stylesheet">
<style>
    .fa{
    width: 1000px;
    background-color: #ccc;
    height: 500px;
    }

    .son{
    width:50%;
    height:50%;
    background-color: #c60;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    }

</style>
</head>
<body>
<div class="fa">

    <div class="son"></div>
</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_41832686/article/details/80271345