css 元素左右居中总结

在日常开发中,经常会遇见居中显示的场景,今天我们来总结几种。

  1. 首先常见的是文字居中,当元素内部有文字是,想让文字居中显示,一般当前元素为块元素使用text-align即可解决
<div>
    <p>居中显示文字</p>
</div>
<style>
div p{
    text-align: center
}
</style>
复制代码
  1. 如果是行内元素,在父级使用text-align可以达到同样的效果
<body>
    <div>
        <span>居中显示文字</span>
    </div>
</body>
<style>
div{
    text-align: center
}
</style>
复制代码
  1. 块元素居中,内部没有文字,宽高一定,使用margin的特性,左右auto可以达到效果
<body>
    <div></div>
</body>
<style>
    div{
        width: 100px;
        margin: 0 auto;
        background-color: #f00;
        height: 20px;
    }
</style>
复制代码

  1. 使用position,宽度已知,根据定位left的50%,可以把元素定在中间,由于css的判定是从元素的左边算起,所以使用margin-left -width/2可以修正元素显示偏移
div{
    width: 100px;
    background-color: #f00;
    position: absolute;
    top: 0;
    left: 50%;
    margin-left: -50px;
}
复制代码
  1. 使用position,如果宽度不能确定
div{
    width: 100px;
    height: 50px;
    background-color: #f00;
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    margin: auto;
}
复制代码

  1. 使用flex justify-content
<body>
    <div>
        <span>显示元素</span>
    </div>
</body>
<style>
    div{
        display: flex;
        justify-content: center;
    }
</style>
复制代码

  1. flex 使用align-item,align-item本来是上下居中的,这里我们使用flex-direction改变元素排列为上下
div{
    display: flex;
    flex-direction: column;
    align-items: center;
}
复制代码
  1. 使用display:table
<body>
    <div>
        <p>显示元素</p>
    </div>
</body>
<style>
    div{
        display: table;
        width: 100%;
        text-align: center;
    }
</style>
复制代码


小tips:
position:absolute; display:flex; display:block; display:table; 都会使元素变成块元素

转载于:https://juejin.im/post/5caa0bd06fb9a05e403a1fa7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值