Justify elements with fix space (variable width)

依然范特西╮ 提交于 2019-12-29 08:44:07

问题


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.

For example this:

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%;
}

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]):

It should work with a different number of child elements.

Is there a professional way to do this with CSS?

EDIT: I should mention that this fix space is a %-value!


回答1:


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; }

Actually, flex: 1 is a shorthand of flex-grow: 1; in this case.




回答2:


You can use display: table and display: table-cell for this:

.container {
  display: table;
  width: 100%;
  border-spacing: 10px 0;
  border-collapse: separate;
  background: palevioletred;
}
.container div {
  display: table-cell;
}
.container img {
  display: block;
  width: 100%;
  height: auto;
}
<div class="container">
  <div><img src="//dummyimage.com/200x100/000/CCC"></div>
  <div><img src="//dummyimage.com/300x100/000/CCC"></div>
  <div><img src="//dummyimage.com/400x100/000/CCC"></div>
</div>
<hr/>
<div class="container">
  <div><img src="//dummyimage.com/200x100/000/CCC"></div>
  <div><img src="//dummyimage.com/400x100/000/CCC"></div>
</div>
<hr/>
<div class="container">
  <div><img src="//dummyimage.com/600x100/000/CCC"></div>
</div>


来源:https://stackoverflow.com/questions/25567897/justify-elements-with-fix-space-variable-width

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!