网站优化

网站优化

Products

当前位置:首页 > 网站优化 >

如何实现CSS文本水平垂直居中?

GG网络技术分享 2025-08-13 12:23 29


文本居中展示

一、 Flexbox布局实现居中

Flexbox布局是一种非常有力巨大的布局方式,能实现许多种元素的居中。在上述示例中,我们用了Flexbox布局,将文本水平和垂直居中。

二、 用定位实现居中

定位是一种老一套的布局方式,能实现元素的绝对居中。

        .container {
            position: relative;
            width: 200px;
            height: 100px;
            border: 1px solid #000;
        }
        .text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate;
            font-size: 18px;
            font-weight: bold;
        }
    

三、 表格单元格方式实现居中

表格单元格方式是一种轻巧松实用的布局方法,能实现元素的水平和垂直居中。

        .container {
            display: table;
            width: 200px;
            height: 100px;
            border: 1px solid #000;
        }
        .text {
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
        }
    

四、 用Grid布局实现居中

Grid布局是一种新鲜的布局方式,给了更丰有钱的布局选项。

        .container {
            display: grid;
            width: 200px;
            height: 100px;
            border: 1px solid #000;
        }
        .text {
            align-self: center;
            justify-self: center;
            font-size: 18px;
            font-weight: bold;
        }
    

五、用百分比宽阔度和margin实现居中

用百分比宽阔度和margin能实现元素的水平和垂直居中。

        .container {
            position: relative;
            width: 50%;
            height: 50%;
            border: 1px solid #000;
        }
        .text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate;
            font-size: 18px;
            font-weight: bold;
        }
    

本文介绍了许多种实现CSS文本水平垂直居中的方法,包括Flexbox、定位、表格单元格、Grid布局等。在实际应用中,能根据需求和场景选择合适的方法。

七、 欢迎验证观点

本文内容仅供参考,实际效果兴许因浏览器和设备而异。欢迎您用实际体验验证本文观点。

标签: 详解 css 文字

提交需求或反馈

Demand feedback