自适应宽高的盒子中文本垂直水平居中

问题:如何让span中的文字在div中垂直水平居中?

方法一:display:table;和display:table-cell;

给父元素div设置position: absolute;display:table;  这样,div就会撑满整个浏览器屏幕;

给需要居中的元素span设置display:table-cell; vertical-align:middle;  这样,span就会撑满div,span中的文字也在span中垂直居中,再用text-align: center;让文字在span中水平居中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        html,body{
            margin: 0;
        }
        .father{
            width: 100%;
            height: 100%;
            background-color: yellow;
            position: absolute;
            display: table;
        }
        .son{
            background-color: lawngreen;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="father">
        <span class="son">我是测试文本</span>
    </div>
</body>
</html>

方法二、不用position: absolute;,而是给html,body设置显性百分比100%。然后给父元素设置display:table,给需要居中的元素设置display:table-cell;vertical-align:middle;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        html,body{
            margin: 0;
            height: 100%;
        }
        .father{
            width: 100%;
            height: 100%;
            background-color: yellow;
            display: table;
        }
        .son{
            background-color: lawngreen;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="father">
        <span class="son">我是测试文本</span>
    </div>
</body>
</html>

方法三、弹性布局flex

给需要其内容居中的元素div设置display:flex;justify-content:center;align-items:center;,这样span在div中垂直水平居中,span是行内元素,文字撑满了span,所以文字在div中也处于垂直水平居中。

如果span转块,有了宽高,那再给span设置display:flex;justify-content:center;align-items:center;让文字在span中垂直水平居中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        html,body{
            margin: 0;
            height: 100%;
        }
        .father{
            width: 100%;
            height: 100%;
            background-color: yellow;
            display: flex;
            /*水平居中*/
            justify-content: center;
            /*垂直居中*/
            align-items: center;
        }
        .son{
            background-color: lawngreen;
        }
    </style>
</head>
<body>
<div class="father">
    <span class="son">我是测试文本</span>
</div>
</body>
</html>

 

小技巧tips:

设置高度、宽度百分比时,百分比是相对于父元素来确定,承接父元素的百分比是相对于浏览器屏幕大小来确定,必须给html,body设置显性百分比100%。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值