![](/img/trans.png)
[英]Is there a way I can have 2 div elements on top of each other but not overlapping?
[英]DIV elements overlapping each other
我正在嘗試使多個 div go 彼此相鄰(在同一行),但它們彼此重疊。
我試過用float: left;
解決這個問題。 或display: inline-block;
但是 div 彼此重疊,而不是在同一行上彼此相鄰。
(我使用了快子 css 工具包)
<link rel="stylesheet" href="https://unpkg.com/tachyons@4.10.0/css/tachyons.min.css"/>
HTML:
<body>
<div id="guesses" class="br3 tc">
<div class="colors">
<div class="br-100 yellow"></div>
<div class="br-100 orange"></div>
</div>
</div>
</body>
CSS:
#guesses {
width: 512px;
height: 512px;
background-color: black;
margin: 0 auto;
margin-top: 64px;
overflow: hidden;
border: black 1px solid;
}
.yellow {
background-color: yellow;
width: 64px;
height: 64px;
position: absolute;
margin: 16px;
}
.orange {
background-color: orange;
width: 64px;
height: 64px;
position: absolute;
margin: 16px;
}
我希望 div 以相同的方式分布在colors
div 中,並且不會溢出。
您首先需要刪除position: absolute
然后使用display: inline-block
沒有問題。
.orange,
.yellow {
display: inline-block;
}
也許您在嘗試的其他地方應用了這個 CSS 規則? 或者也許保留您的position: absolute
?
您可以使用 CSS 屬性來執行此操作 - display: flex;
您還需要移除 position。
這是工作代碼:
#guesses { width: 512px; height: 512px; background-color: black; margin: 0 auto; margin-top: 64px; overflow: hidden; border: black 1px solid; }.yellow { background-color: yellow; width: 64px; height: 64px; margin: 16px; display: inline-block; }.orange { background-color: orange; width: 64px; height: 64px; margin: 16px; display: inline-block; }
<div id="guesses" class="br3 tc"> <div class="colors"> <div class="br-100 yellow"></div> <div class="br-100 orange"></div> </div> </div>
您最好在父級上使用display: flex
並在子級上使用display: inline-flex
。 此外,添加justify-content: center
將為您將孩子居中。 我在您的 colors 中添加了一個額外的 class,以便我們可以重新利用它。 希望能幫助到你!
#guesses { width: 512px; height: 512px; background-color: black; margin: 0 auto; border: black 1px solid; }.colors { display: flex; justify-content: center; }.color { display: inline-flex; }.yellow { background-color: yellow; width: 64px; height: 64px; }.orange { background-color: orange; width: 64px; height: 64px; }
<body> <div id="guesses" class="br3 tc"> <div class="colors"> <div class="br-100 yellow color"></div> <div class="br-100 orange color"></div> </div> </div> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.