相对于祖父母div的大小设置宽度



我的结构目前看起来与下面的片段大致相似;如何使div2的宽度为其祖父母div的50%,而不是直系父母div的50%?

<div id="grandParent" style="width: 100%; display: flex; flex-direction: row; flex-wrap: nowrap; background-color: yellow; border-color: yellow">
<div id="div1" style="width: 100px; background-color: aqua">
div1
</div>
<div id="parent" style="width: 100%; background-color: green">
parent<br>
<div id="div2" style="width: 50%; background-color: fuchsia; margin: 0 auto;">
div2
</div>
</div>
</div>

我们可以做一些数学运算。父对象的宽度是P - 100px,您需要有P/2,所以如果您在X = P - 100px处执行X/2 + 50px,您将有P/2。最好使用flex-grow:1而不是width:100%来避免收缩效应,并使第一个div始终位于100px

console.log($('#div2').width())
console.log($('#grandParent').width())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grandParent" style=" display: flex; flex-direction: row; flex-wrap: nowrap; background-color: yellow; border-color: yellow">
<div id="div1" style="width: 100px; background-color: aqua">
div1
</div>
<div id="parent" style="flex-grow:1; background-color: green">
parent<br>
<div id="div2" style="width: calc(50% + 50px); background-color: fuchsia; margin: 0 auto;">
div2
</div>
</div>
</div>

您可以考虑使用CSS变量使其更容易:

console.log($('#div2').width())
console.log($('#grandParent').width())
:root {
--w:100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grandParent" style="display: flex; flex-direction: row; flex-wrap: nowrap; background-color: yellow; border-color: yellow">
<div id="div1" style="width: var(--w); background-color: aqua">
div1
</div>
<div id="parent" style="flex-grow:1;background-color: green">
parent<br>
<div id="div2" style="width: calc(50% + var(--w)/2); background-color: fuchsia; margin: 0 auto;">
div2
</div>
</div>
</div>

最新更新