簡體   English   中英

CSS將div垂直向下移動

[英]CSS moving a div vertically down

我試圖將另一個div內的div向下移動一點,但是當我使用

margin-top: 10px;

它在頂部形成白色縫隙。 繼承人的HTML:

<div id="topb">
    <div id="selection">

    </div>
</div>

這是CSS:

#topb {
    background: url(images/tomato-background.jpg) no-repeat fixed;
    background-size: cover;
    height: 100%;
    width: 101%;
    margin-left: -10px;
}

#selection {
    background-color: #4d4d4d;
    width: 60%;
    height: 500px;
    margin: auto;
    margin-top: 40px;
}

這是網站的屏幕截圖: 圖片

刪除#selection中的margin-top樣式,並將padding-top應用於#topb

這是一個“折疊邊距”問題。 已回答以下問題: 為什么父元素不包含邊距?

您必須將父div更改為(1)添加邊框,(2)絕對位置,(3)顯示為行內塊,(4)自動溢出。

請參閱發布的鏈接以獲取更多詳細信息。

也許您可以通過添加padding-top:10px;來修改父元素padding-top:10px; 而不是修改孩子。

為此,您可以使用position: absolute 這是代碼:

 #topb { background: url(images/tomato-background.jpg) no-repeat fixed; background-size: cover; height: 100%; width: 101%; margin-left: -10px; } #selection { background-color: #4d4d4d; width: 60%; height: 500px; margin: auto; position: absolute; top: 40px; /*This is where it is changed as well as the line above*/ } 

希望能幫助到你! 我認為填充仍然會留下背景,因此這是一個更好的主意。

這是工作中的提琴,希望對您有所幫助。

position:absolute;
position:relative;

這是因為當您在另一個圖塊元素中包含一個圖塊元素(顯示:圖塊)時,邊距將收縮。 它只會被認為是最大的保證金。

因此,在您的示例中,它將僅考慮邊距之一(40像素)。 請參見有關邊距崩潰的參考

有一些解決方法。 選擇任何:

  1. 使用padding而不是內部組件的margin
  2. 更改display類型。 例如display: inline-block
  3. 使用absolute定位。

暫無
暫無

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

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