我有许多DIV元素,我想并排显示(在屏幕分辨率允许的情况下)。以前,我使用display: inline-block
实现此目的。但是,DIV元素的内容是动态的,当开始出现换行符时,它看起来不整洁。
CSS网格似乎能够解决此问题,但是我正在努力解决的最后一个难题。
repeat
与minmax()
一起使用时,当div扩展以填充空白时,会创建未使用的空白。我需要防止div扩展超出其内容的大小,因为在大屏幕上,这会使它们之间的距离过大:
是否有任何方法可以防止网格单元(或div)扩展到空白区域?
SCSS在下面,并附带CodePen here:
.SideBySideContainer {
> div {
border: 1px solid red;
padding:1em;
}
}
@media all and (max-width: 899px) {
/* Small screens (will be improved to use @supports for grid support) */
.SideBySideContainer {
> div {
display: inline-block;
vertical-align: top;
}
> div:not(:last-of-type) {
margin-right: 1em;
}
> div:first-of-type {
max-width: calc(50% - 2em);
}
}
}
@media all and (min-width: 900px) {
.SideBySideContainer {
display: grid;
grid-gap: 1em;
grid-auto-flow: dense;
grid-auto-rows: minmax(5em, auto);
&.FourCols {
/* Problem seems to be with minmax() here */
grid-template-columns: repeat(auto-fill, minmax(10em, 20%));
}
}
}
建议的答案是使用inline-flex
。但是,当内容冗长时,这看起来很可怕,并导致两个问题:
在立即嵌套的div上设置最大宽度
.SideBySideContainer > div {
border: 1px solid red;
padding: 1em;
margin: 1em;
}
@media all and (max-width: 899px) {
/* Small screens (will be improved to use @supports for grid support) */
.SideBySideContainer > div {
display: inline-block;
vertical-align: top;
}
.SideBySideContainer > div:not(:last-of-type) {
margin-right: 1em;
}
.SideBySideContainer > div:first-of-type {
max-width: calc(50% - 2em);
}
}
@media all and (min-width: 900px) {
.SideBySideContainer {
display: inline-flex;
}
.SideBySideContainer.FourCols > div {
max-width: calc(100% / 4);
}
}
<div class="SideBySideContainer FourCols">
<div>
<h3>Block 1</h3>
<p>
<select>
<option val="">Foo</option>
</select>
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
</div>
<div>
<h3>Block 2</h3>
<p>
<select>
<option val="">Bar</option>
</select>
</p>
</div>
<div>
<h3>Block 3</h3>
<p>
<select>
<option val="">Foo Bar</option>
</select>
</p>
</div>
<div>
<h3>Block 4</h3>
<p>
<select>
<option val="">Bar Foo</option>
</select>
</p>
</div>
</div>