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>
Snipaste_2019-04-07_22-14-52.png
  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;
}
Snipaste_2019-04-07_22-24-31.png
  1. 使用flex justify-content
<body>
    <div>
        <span>显示元素</span>
    </div>
</body>
<style>
    div{
        display: flex;
        justify-content: center;
    }
</style>
Snipaste_2019-04-07_22-28-02.png
  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>
Snipaste_2019-04-07_22-37-07.png

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容