我有 parent 、 child 和孙子 div
。孙子需要显示在行中,而不是列中。我试图让 child 与孙子( child 的 child )具有相同的宽度,但与此同时,我希望 parent 保留其孙子的高度。
我试着让 child 到 position: absolute
,但问题是, parent 不保留 child 和孙子的高度。
如何使父级与其后代具有相同的高度,同时具有不同的宽度。 child 的宽度是否与孙子的宽度相同?
JSFiddle
*,
*:before,
*:after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#wrapper {
background-color: lightblue;
width: 220px;
}
#innerWrapper {
display: flex;
background-color: blueviolet;
}
.item {
background-color: tomato;
width: 100px;
height: 100px;
border: 1px solid blue;
margin: 5px;
flex: 1 0 auto;
}
#other {
background-color: yellow;
width: 300px;
height: 250px;
}
<div id="wrapper">
<div id="innerWrapper">
<div class="item">Item - 1</div>
<div class="item">Item - 2</div>
<div class="item">Item - 3</div>
<div class="item">Item - 4</div>
<div class="item">Item - 5</div>
<div class="item">Item - 6</div>
</div>
</div>
<div id="other">I'm another element</div>
最佳答案
更新
通缉令:
- 奶奶在 220px,所以我给了她
max-width:220px
- 妈妈给 children 穿衣服,就像从奶奶身边伸出来的收缩包装一样。我给了她
position:relative
来逃避奶奶的流量,min-width: 635px
这是 child 宽度的总和,包括边距,min-height:110px
这是 child 的高度加上边距。 kids
display: inline-block
,position: absolute
。然后,我使用此nth
选择器给了他们一个left
的累积值间隔 105px:div div div:nth-of-type(X) { left:105px++ }
查看代码片段以获得更清晰的图片。
妈妈有一个半透明的背景,所以你可以看到黑色的奶奶。
#other
被赋予 position:relative
和 top:110px
以将其移开。
我想我明白你在追求什么。在这个片段中,我给出了:
<德尔>1。奶奶 display:table
和 table-layout:fixed
<德尔>2。妈妈 display:table-row
<德尔>3。 children display:table-cell
我添加了虚线边框、border-spacing
和半透明背景以显示奶奶和妈妈的存在。这些添加是可选的。我也删除了 flexbox 属性。
片段(修订版)
*,
*:before,
*:after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#wrapper {
background-color: black;
max-width: 220px;
float: left;
}
#innerWrapper {
background-color: rgba(0, 0, 200, .5);
display: inline-block;
position: relative;
display: flex;
min-width: 635px;
min-height: 110px;
}
.item {
background-color: tomato;
width: 100px;
height: 100px;
border: 1px solid blue;
margin: 5px;
display: inline-block;
position: absolute;
}
div div div:nth-of-type(2) {
left: 105px;
}
div div div:nth-of-type(3) {
left: 210px;
}
div div div:nth-of-type(4) {
left: 315px;
}
div div div:nth-of-type(5) {
left: 420px;
}
div div div:nth-of-type(6) {
left: 525px;
}
#other {
background-color: yellow;
width: 300px;
height: 250px;
position: relative;
top: 110px;
}
<div id="wrapper">
<div id="innerWrapper">
<div class="item">Item - 1</div>
<div class="item">Item - 2</div>
<div class="item">Item - 3</div>
<div class="item">Item - 4</div>
<div class="item">Item - 5</div>
<div class="item">Item - 6</div>
</div>
</div>
<div id="other">I'm another element</div>
关于html - 使父 div 与子宽度相同,并忽略父 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40570687/