• 技术文章 >web前端 >前端问答

    css文字如何垂直居中

    藏色散人藏色散人2021-04-29 09:15:50原创1863

    css实现文字垂直居中的方法:1、使用line-height属性使文字垂直居中;2、将外部块格式化为表格单元格;3、通过CSS3的flex布局使文字垂直居中。

    本文操作环境:windows7系统、HTML5&&CSS3版、Dell G3电脑。

    方法:

    方法1:使用line-height属性使文字垂直居中

    line-height属性设置行间的距离(行高);该属性不允许使用负值。

    line-height属性会影响行框的布局。在应用到一个块级元素时,它定义了该元素中基线之间的最小距离而不是最大距离。

    line-height 与 font-size 的计算值之差(在 CSS 中成为“行间距”)分为两半,分别加到一个文本行内容的顶部和底部。可以包含这些内容的最小框就是行框。

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>css 垂直居中</title>
            <style>
                .box{
                    width: 300px;
                    height: 300px;
                    background: #ddd;
                    line-height:300px;
                }
            </style>
        </head>
        <body>
            <div class="box">css 垂直居中了--文本文字</div>
        </body>
    </html>

    效果图:

    35ccbc6abc1f20a97d2c22760dc6e3b.png

    方法2:将外部块格式化为表格单元格

    表格单元格的内容可以垂直居中,将外部块格式化为表格单元格就可垂直居中文本。

    示例:将段落置于具有特定给定高度的块内

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>css 垂直居中</title>
            <style>
                .box{
                    width: 400px;
                    height: 200px;
                    background: #ddd;
    display: table-cell;
    vertical-align: middle;
                }
            </style>
        </head>
        <body>
            <div class="box">css 垂直居中了--文本文字</div>
        </body>
    </html>

    效果图:

    33a4a32624e9126886f2020a68c0d89.png

    方法3:使用CSS3的flex布局 使文字垂直居中

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>css 垂直居中</title>
            <style>
                .box{
                    width: 300px;
                    height: 200px;
                    background: #ddd;
                     /*设置为伸缩容器*/
                    display: -webkit-box;
                    display: -moz-box;
                    display: -ms-flexbox;
                    display: -webkit-flex;
                    display: flex;
                    /*垂直居中*/
                    -webkit-box-align: center;/*旧版本*/
                    -moz-box-align: center;/*旧版本*/
                    -ms-flex-align: center;/*混合版本*/
                    -webkit-align-items: center;/*新版本*/
                    align-items: center;/*新版本*/
                }
            </style>
        </head>
        <body>
            <div class="box">css 垂直居中--文本文字(弹性布局)</div>
        </body>
    </html>

    效果图:

    53ae0b936a0c68c28ad82f87d58d32d.png

    更多详细的HTML/CSS知识,请访问CSS视频教程栏目!

    以上就是css文字如何垂直居中的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:css
    上一篇:div css怎么实现隐藏滚动条 下一篇:怎么添加css样式
    大前端线上培训班

    相关文章推荐

    • css文件应该放在哪• css怎么使用display显示隐藏元素• css如何设置元素不可见• div css怎么实现隐藏滚动条

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网