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

相關文章
相關標籤/搜索