用固定空间(可变宽度)对齐元素 [英] Justify elements with fix space (variable width)
问题描述
我有一个容器中有可变数量的元素。
元素应该是对齐的,但是之间有一个修复空间(例如 20px
)。
这意味着每个元素的宽度必须适应。
I have a container with a variable number of elements in it.
The elements should be justified but with a fix space between (e.g. 20px
).
That means the width of every element has to adapt.
例如:
HTML
<div class="container">
<div>
<img src="...">
</div>
<div>
<img src="...">
</div>
<div>
<img src="...">
</div>
</div>
CSS
div.container {
text-align: justify;
}
div.container div {
display: inline-block;
margin-right: 20px;
}
div.container div img {
width: 100%;
}
最后应该看起来像这样元素和3个元素;宽度是动态的,但是空间修复[20px]):
At the end it should look like this (this picture shows two examples: 2 elements and 3 elements; the width is dynamic but the space fix [20px]):
它应该与不同数量的子元素配合使用。
是否有专业的方法使用CSS?
Is there a professional way to do this with CSS?
EDIT :我应该提到修复空间是%值!
EDIT: I should mention that this fix space is a %-value!
推荐答案
如果使用 Flexbox 是一个选项,您可以向flex项目添加 flex:1
具有固定值的margin属性如下:
If using Flexbox is an option, you could add flex: 1
to the flex items and also a margin property with a fixed value as follows:
EXAMPLE HERE
div.container { display: flex; }
div.container div {
height: 50px; /* Just for demo */
flex: 1;
margin-left: 20px;
}
div.container :first-child { margin-left: 0; }
其实, flex:1
flex-grow:1; 的简写: code>
。
Actually, flex: 1
is a shorthand of flex-grow: 1;
in this case.
这篇关于用固定空间(可变宽度)对齐元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!