首頁  >  文章  >  web前端  >  為什麼 `margin: auto;` 不能在內聯區塊元素上運作?

為什麼 `margin: auto;` 不能在內聯區塊元素上運作?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-26 13:04:29350瀏覽

Why Doesn't `margin: auto;` Work on Inline-Block Elements?

邊距:自動;不適用於內聯塊元素

在 CSS 中,margin:auto;通常用於在頁面上水平居中塊元素。但是,當應用於內聯塊元素時,此屬性變得無效。

內聯塊元素像內聯元素一樣內嵌到頁面中,但可以具有特定的寬度和高度。當嘗試使用 margin:auto; 將它們水平居中時,此行為會產生困難。

舊程式碼:

<code class="css">#container {
    /* Other styles... */
}
.center {
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}</code>

在此程式碼中,#container 元素有一個特定寬度並觸發預期的居中行為。

新程式碼:

<code class="css">#container {
    /* Other styles... */
    display: inline-block;
}
.center {
    margin: 75px auto;
    position: relative;
}</code>

將 #container 的顯示屬性改為 inline-block 會改變它與邊距互動的方式。內聯塊元素的行為與區塊元素不同,且無法使用 margin:auto; 居中。

解:

將內聯塊元素居中水平方向,請在其包含元素上使用text-align: center 屬性:

<code class="html"><div class="center">
  <div class="MtopBig" id="container"></div>
</div></code>
<code class="css">.center {
    text-align: center;
}</code>

這會將內聯塊元素與其包含塊元素的中心對齊。

以上是為什麼 `margin: auto;` 不能在內聯區塊元素上運作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn