Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

html - Justify elements with fix space (variable width)

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

picture showing elements

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...