【css基础修炼之路】— 谈谈元素的垂直水平居中

作为一个初级的前端工程师,在开发的过程中遇到了许多问题,其中使元素垂直居中这个问题难住了我,可能在大家看来这是一个非常小的问题,但是却困扰了我很长时间,于是决定做一个总结!!!

废话不多说,直接上代码,里面有我的思考过程

案例一

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>div实现垂直居中</title>
</head>
<style>
.abc {
     200px;
    height: 200px;
    background: green;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

.box {
    position: relative;
     500px;
    height: 500px;
    background: red;
    display: inline-block;
}
</style>
<div class="box">
    <div class="abc"> </div>
</div>

<body>
</body>

</html>

案例二(文字的水平垂直居中)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <style>
    div {
        height: 300px;
         200px;
        display: table;
        background: #666;
    }

    span {
        display: table-cell;
        vertical-align: middle;
    }
    </style>
    <div>
        <span>我是span</span>
    </div>
</body>

</html>

案例三

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>div实现垂直居中</title>
</head>
<style>
.abc {
     200px;
    height: 200px;
    background: green;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
}

.box {
    position: relative;
     500px;
    height: 500px;
    background: red;
    display: inline-block;
}
</style>
<div class="box">
    <div class="abc"> </div>
</div>

<body>
</body>

</html>

案例四

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>div实现垂直居中</title>
</head>
<style>
/*
table-cell实现居中
将父盒子设置为table-cell元素,设置
text-align:center,vertical-align: middle;
子盒子设置为inline-block元素
*/

.ok {
     200px;
    height: 200px;
    background: red;
    display: table-cell;
    /*这个必须是table-cell*/
    /*父级是一个小表格,表格默认是放文字的,子集是一个小果冻元素,给父级设置vertical-align:middle使元素垂直居中*/
    text-align: center;
    vertical-align: middle;
}

.innerBox {
     100px;
    height: 100px;
    background: green;
    display: inline-block;
    /*注意:里面的元素必须是inline-block*/
}
</style>

<body>
    <div class="ok">
        <div class="innerBox">
        </div>
    </div>
</body>

</html>

案例五

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <style>
    /* 注意:该方法值适合文字的水平垂直居中;
     * 父级高度固定,嵌套行内元素
     *关键属性:父级:diaplay:tabel; 子集:display:tabel-cell; vertical-align:middle;
     */

    .div {
        height: 300px;
         200px;
        display: table;
        /*这么理解:父级是一个固定宽度高度的大表格*/
        background: #666;
    }

    .span {
        display: table-cell;
        /* 子集是父级表格里面的一个小格,设置display:table-cell,给父级设置垂直居中*/
        vertical-align: middle;
    }
    </style>
    <div class="div">
        <div class="span">sddddd</div>
    </div>
</body>

</html>
记住,在你成功之前,每前进一步遇到的都将是更大的困难,所以微笑面对每一个困难 -----至有理想的自己
原文地址:https://www.cnblogs.com/-yu-ze-/p/8592140.html