css 元素左右居中总结

在平常开发中,常常会碰见居中显示的场景,今天咱们来总结几种。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; 都会使元素变成块元素html

相关文章
相关标签/搜索