在div中设置文字与内部div垂直居中

在div中设置文字与内部div垂直居中

要实现如图一所示的结果:

html代码如下:

复制代码

<!DOCTYPE html>
<html>

<head lang="zh">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8" />
    <title>商品管理后台首页</title>
    <link rel="stylesheet" href="./css/index.css" />
</head>

<body>
    <div class="content">
        <span>这是一个测试要居中</span>
        <div class="box">我是div中的文字</div>
    </div>
</body>

</html>

复制代码

相应的less代码

复制代码

.content{
    width: 500px;
    height: 200px;
    border:1px solid red;
    position: relative;
    line-height: 200px;/*让class=content父div中的文字垂直居中*/
    span{
        background: green;
    }
    .box{
        background: yellow;
        float: left;
        width: 200px;
        height: 100px;
        line-height: 100px;/*让黄色div中的文字内容垂直居中*/
        text-align: center;/*让文字水平居中*/
        position: absolute;
        top:50%;
        margin-top: -50px;
        margin-left: 200px;    
    }
}

复制代码


②使用vertical-align:middle设置在父元素中的位置,

效果图:

html代码:

复制代码

<!DOCTYPE html>
<html>
<head lang="zh">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8" />
    <title>商品管理后台首页</title>
    <link rel="stylesheet" href="./css/index.css" />
</head>

<body>
    <div class="content">
        我是div中的文字<div class="pox">我是子元素的文字</div>
    </div>
</body>

</html>

复制代码

相应的css代码:

复制代码

.content{
    width: 500px;
    height: 200px;
    line-height: 200px;/*设置其文字内容垂直居中*/
    border:1px solid red;
    .pox{
        background: yellow;
        width: 200px;
        height: 70px;
        display: inline-block; /*一定要将div设置为inline-block*/
        vertical-align: middle;/*设置该元素在父元素中的位置*/
        line-height: 70px;
        border: 1px solid green;
        text-align: center;
    }
}

 化简后的核心代码:

.content{
    width: 500px;
    height: 200px;
    line-height: 200px;/*设置其文字内容垂直居中*/
    background:red;
    .pox{
        height: 70px;/*给内部div设置了高度,该div才会垂直居中*/
         display: inline-block; /*一定要将div设置为inline-block*/
        vertical-align: middle;/*设置该元素在父元素中的位置*/
        background: yellow;
    }
}            
发布了16 篇原创文章 · 获赞 208 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/cxu123321/article/details/103994510