如何让设置浮动的元素垂直居中

Posted web-record

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何让设置浮动的元素垂直居中相关的知识,希望对你有一定的参考价值。

浮动元素垂直居中:

1.核心代码: vertical-align: middle;display: table-cell;代码实现如下

<style type="text/css">
    #demo {
          width: 300px;
          height: 200px;
          background-color: grey;
          display: table-cell;
          vertical-align: middle;
    }
    .fl {

        float: left;
        width: 50px;
        height: 50px;
        background-color: black;
     }
</style>
<body>
    <div id="demo">
        <div class="fl"></div>
    </div>
</body>

2.使用flex布局

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .clearFix::after{
            display:block;
            clear:both;
            content:"";
            visibility:hidden;
            height:0
        }
        .clearFix{
            zoom: 1;
        }
        .container{
            width: 100%;
            height: 800px;
            background-color: blue;
            
            display: flex;
            /* 垂直居中 */
            align-items: center;
            /* 水平居中 */
            justify-content:center;
        }
        .child1{
            width:200px;
            height:200px;
            background-color: red;
        }
        .child2{
            width:200px;
            height: 200px;
            background-color: goldenrod;
        }
        .lf{
            float: left;
        }
    </style>
</head>
<body>
    <div class="container clearFix">
        <div class="child1 lf">child1</div>
        <div class="child2 lf">child2</div>
    </div>
</body>
</html>

以上是关于如何让设置浮动的元素垂直居中的主要内容,如果未能解决你的问题,请参考以下文章

如何让一个浮动元素既水平又垂直居中

让浮动元素垂直居中

如何让div中的行内元素的文字垂直居中

用CSS 实现元素垂直居中,都有哪些好的方案

如何垂直居中一个浮动元素

如何垂直居中一个浮动元素