簡體   English   中英

頁面底部居中div的問題

[英]Problem to center div on bottom of the page

我有 2 個容器:我想將第一個放在頂部並將其居中(使用margin:0 auto;執行此操作沒問題)。

但是,我無法將第二個放在底部中央。

我正在嘗試將 div 與底部位置的中心對齊(類似於頁腳 div,但寬度不是 100%)。 我的 div 寬度為 90%,無法居中。 它總是左對齊。 如果我使用margin: 0 auto; 它轉到中心但不在頁面底部。 如果我使用position: absolute; bottom:0; position: absolute; bottom:0; 它位於頁面底部但未與中心對齊。

有人有解釋嗎?

PS:我想保持 HTML 不變,而不是創建另一個 div 來包含第二個 div。

 .a { width: 90%; height: 10%; background-color: beige; margin: 0 auto; }.b { position: fixed; width: 90%; height: 10%; margin: 0 auto; bottom: 0; background-color: aliceblue; }
 <div class="a">A</div> <div class="b">B</div>

因此,使用position: fixed你已經有效地將那個元素從 DOM 流中分離出來,所以margin: 0 auto現在是無關緊要的,相反你會想要做其他幾個選項之一來實現你的目標。 幾個例子(注意:片段編輯器不會做position: fixed well 所以你會想在本地嘗試);

 .a { width: 90%; height: 10%; background-color: beige; margin: 0 auto; }.b { position: fixed; bottom: 0; left: 5%; right: 5%; height: 10%; background-color: aliceblue; }
 <div class="a">A</div> <div class="b">B</div>

要么,

 .a { width: 90%; height: 10%; background-color: beige; margin: 0 auto; }.b-container { position: fixed; bottom: 0; left: 0; right: 0; }.b { margin: 0 auto; width: 90%; height: 10%; background-color: aliceblue; }
 <div class="a">A</div> <div class="b-container"> <div class="b">B</div> </div>

希望這會有所幫助,干杯。

我沒有足夠高的聲譽來評論答案,但你可以使用

left: 0; right: 0;

在 your.b div 上,而不必在其周圍放置一個容器。 我試過了並且在谷歌瀏覽器下工作。

這里有更多解釋 - CSS Fixed position with Auto Margin

.b以下內容:

left: 5%;

margin: auto不適用於絕對定位的元素,僅適用於靜態元素。

你想要頁眉和頁腳嗎? 而頁腳總是在底部? 使用更現代的彈性布局來做到這一點。

https://stackblitz.com/edit/html-header-main-footer?embed=1&file=style.css

<body>
  <header>Header</header>
  <main>Main</main>
  <footer>Footer</footer>
</body>
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}

body {
  display: flex;
  align-items: center;
  flex-direction: column;
}

header, main, footer {
  width: 100%;
  max-width: 600px;
  text-align: center;
}

main {
  flex: 1;
}

問:它是如何工作的?
A: 主要是一個彈性墊片。

PS: header, main 和 footer 只是一個建議。 您也可以只使用 div。

@chris ..... 解決方案 A 不起作用,BI 希望保持不變 html @utkanos .....左:5% 很好,但我不想計算中間空間(如果寬度為 775 像素,圖像) @Dominik .... div 不是全寬的,2 個容器的寬度可能不同

我不確定除了這兩個 div 之外還有什么其他 HTML。 你會在“a”和“b”之間有一個div嗎? 所有的 div 周圍都會有一個包裝 div 嗎? 您可以將 CSS 網格用於您的解決方案。

這是 CSS:

    /* ideally this would be on a wrapper div instead of the body tag */
    body {
    display: grid;
    grid-template-rows: 90px 1fr 90px; /*This is the row heights*/
    grid-template-columns: 1fr;
    height: 100vh;
    width:90%;
    margin:0 auto;
    }

    .a {
    grid-row: 1 / 2;
    background-color: beige;
    }

    .b {
    grid-row: 3 / 4;
    background-color: aliceblue;
    }

那么您的標記將保持不變:

    <div class="a">A</div>   
    <div class="b">B</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM