css设置元素居中总结

水平居中

块级元素

flex布局(设置在父元素)

display:flex;
justify-content:center;

grid布局(设置在父元素)

display:grid;
justify-content:center

水平居中和垂直居中同时设置

place-items: center;

绝对定位(设置在子元素)

position:absolute;
left:-50%;
//1.使用transform
transform: translate(-50%, 0);
//2.使用margin
margin-left:-width*50%

浮动元素水平居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .parent {
            margin: 0 auto;
            width: -moz-fit-content;
            width: -webkit-fit-content;
            width:fit-content;
        }
        .son{
            float: left;
            background: pink;
            width:50px;
            height:50px;
        }
    </style>
</head>
<body>
    <div class='parent'>
        <div class="son">

        </div>
    </div>
</body>
</html>

fit-content是CSS3中给width属性新加的一个属性值,它配合margin可以轻松实现水平居中, 目前只支持Chrome 和 Firefox浏览器

行内元素

父元素设置text-align:center

垂直居中

块级元素

flex布局(设置在父元素)

display:flex;
align-item:center;

grid布局(设置在父元素)

display:grid;
align-item:center;

水平居中和垂直居中同时设置

place-items: center;

绝对定位(设置在子元素)

position:absolute;
top:-50%;
//1.transform
transform:tranlate( 0, -50%);
//2.margin
margin-top:-height*50%

table

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .parent {
            background: #ccc;

            display: table;
        }
        .son{
            background: pink;

            display: table-cell;
            vertical-align: middle;
        }
    </style>
</head>
<body>
    <div class='parent'>
        <div class="son">123</div>
    </div>
</body>
</html>

使用 display: table; 可以模拟表格布局的特点,例如自动等分列宽和自动增长行高等。但与使用真正的HTML表格相比,使用 display: table; 具有更多的灵活性,因为它不会限制你只能使用特定的表格元素(如 <tr><td> 等),而是可以在任何元素上应用这些属性。

display: table-cell;: 将元素呈现为表格单元格。

display: table-row; 将元素呈现为表格行。

display: table-header-group;display: table-footer-group;: 将元素分别呈现为表格的页眉组和页脚组。

行内元素
height:50px;
line-height:50px;

行高与高度一致

本文由博客一文多发平台 OpenWrite 发布!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值