我一直試圖在 CSS 中有兩個框,一個在另一個的右上角。我一直在嘗試嵌套 div 并使用相對定位,但我不知道該怎么做。有人能幫我嗎?(不使用 z 索引)
uj5u.com熱心網友回復:
如果我正確理解您希望一個盒子位于另一個盒子內,您可以使用、和移動position: relative內框來實作此目的。toprightleftbottom
我建議深入了解CSS 位置的 MDN 頁面以獲取更多資訊。
.box1, .box2 {
display: inline-block;
}
.box1 {
width: 200px;
height: 200px;
background: green;
}
.box2 {
position: relative;
width: 100px;
height: 100px;
top: -100px;
left: -100px;
background: orange;
}
<div class='box1'></div>
<div class='box2'></div>
uj5u.com熱心網友回復:
你可以使用這樣的東西。使用 flexBox 對齊它們并給第二個盒子一個負邊距。
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
min-height: 100vh;
margin: 0;
background-color: bisque;
display: grid;
place-content: center;
}
.container{
display: flex;
flex-direction: row;
}
.first{
height: 5rem;
width: 5rem;
background-color: tomato;
}
.second{
margin-top:-50%;
height: 5rem;
width: 5rem;
background-color: tomato;
}
<div class="container">
<div class="first"></div>
<div class="second"></div>
</div>
根據馬科斯的回答,我認為我理解錯了。
這是獲得所需結果的簡單方法。您可以使用position:relative父項和position: absolute子項。然后你可以在里面移動子元素。top:0;將帶你到上角,right:0;并帶你到右角。
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
min-height: 100vh;
margin: 0;
background-color: bisque;
display: grid;
place-content: center;
}
.parent{
width: 10rem;
height: 10rem;
background-color: tomato;
position: relative;
}
.child {
width: 5rem;
height: 5rem;
background-color: aqua;
position: absolute;
top:0;
right: 0;
}
<div class="parent">
<div class="child"></div>
</div>
uj5u.com熱心網友回復:
我不由自主地想到了兩種可能性。1) 使用“倉位”或 2) 使用“保證金”。
這里是一個結合彈性框邊距的例子;
.w {
background-color: lightgray;
display: flex;
justify-content: center;
padding: 20px;
}
.a, .b {
width: 150px;
height: 150px;
}
.a {
background-color: lightblue;
}
.b {
background-color: lightgreen;
margin-top: 20px;
margin-left: -20px;
}
<div class="w">
<div class="a">A</div>
<div class="b">B</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/468658.html
上一篇:在css中布局網格專案
