gpt4 book ai didi

javascript - 防止 Div 以百分比宽度开始新行

转载 作者:太空宇宙 更新时间:2023-11-04 11:09:47 26 4
gpt4 key购买 nike

我在另一个 div 中有几个 div,我希望用户能够调整这些 div 的大小,但它们应该保持百分比宽度。此示例显示 6 个宽度为 18% 的 div,它们加起来超过 100%,第 6 个 div 开始一个新行:

http://jsfiddle.net/v3o3vqqo/

div { 
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}

.container {
width: 100%;
}

.inner {
width: 18%;
float: left;
margin: 1px;
}

.red {
background-color: red;
}

.orange {
background-color: orange;
}

.yellow {
background-color: yellow;
}

.green {
background-color: green;
}

.blue {
background-color: blue;
}

.purple {
background-color: purple;
}
<h4>The goal</h4>
<p>Get all the boxes to fit on one line, with equal width.</p>

<div class="container"><div class="inner red">&nbsp;</div><div class="inner orange">&nbsp;</div><div class="inner yellow">&nbsp;</div><div class="inner green">&nbsp;</div><div class="inner blue">&nbsp;</div><div class="inner purple">&nbsp;</div>
<!-- Plus arbitrarily many more boxes... -->
</div>

我希望它显示 2 个 child ,因为他们的宽度是 100% 在一起并且 2 个 child 溢出(这意味着我需要滚动才能看到另一个。

问题是,如果父级的宽度为 100% 而子级的总和超过 100%,它们会另起一行而不是导致水平滚动。

所以我的问题是如何导致水平滚动?

最佳答案

您无法使用 float 实现此目的。您将不得不使用不同的布局。

你可以使用 flexbox。默认情况下它有 flex-wrap: nowrap,所以没有换行。

您将需要使用 flex-shrink: 0 来防止当 flex 元素占用的空间多于可用空间时收缩。

.container {
display: flex;
overflow: auto;
}
.inner {
width: 18%;
height: 2em;
flex-shrink: 0;
}
<h4>The goal</h4>
<p>Get all the boxes to fit on one line, with equal width.</p>
<div class="container">
<div class="inner" style="background: red"></div>
<div class="inner" style="background: orange"></div>
<div class="inner" style="background: yellow"></div>
<div class="inner" style="background: green"></div>
<div class="inner" style="background: blue"></div>
<div class="inner" style="background: purple"></div>
</div>

或者,您可以使用 inline-block,并使用 white-space: nowrap 防止换行。但是,请注意 How to remove the space between inline-block elements?

.container {
overflow: auto;
white-space: nowrap;
}
.inner {
display: inline-block;
width: 18%;
height: 2em;
}
<h4>The goal</h4>
<p>Get all the boxes to fit on one line, with equal width.</p>
<div class="container">
<div class="inner" style="background: red"></div
><div class="inner" style="background: orange"></div
><div class="inner" style="background: yellow"></div
><div class="inner" style="background: green"></div
><div class="inner" style="background: blue"></div
><div class="inner" style="background: purple"></div>
</div>

关于javascript - 防止 Div 以百分比宽度开始新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33712299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com