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
588 views
in Technique[技术] by (71.8m points)

html - How to spread elements horizontally evenly?

I have a div container on my web page with fixed width and it contains form elements for logging in. Below these elements there are a submit button, forgotten password link etc.

It happens the last line elements need fewer width than the box provides. How to spread them evenly? I don't want

  • default
| A B C           |
  • centering the line like
|      A B C      |
  • nor table layout
|  A  |  B  |  C  |


Instead I am looking for some CSS way to achieve:

|  A    B    C  |

That is:

  • put about equal space between all elements
  • center the whole thing to avoid the first or last to the side

edit: This answer worked best. I created templates for 2 or 3 elements like this:

div.spread2evenly > div {
    display: inline-block;
    *display: inline; /* For IE7 */
    zoom: 1; /* Trigger hasLayout */
    width: 50%;
    text-align: center;
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

CSS3 flexboxes have better browser support now, although you may need to add additional vendor prefixes for more browser coverage.

Modern Approach:

Just change the display of the container element to flex and then utilize the justify-content property to specify how the browser should distribute the space around and between the flex items along the main axis.

In the example below, you will notice that justify-content: space-around or justify-content: space-between are used to space the elements out evenly.

.container {
  display: flex;
}
.container.space-around {
  justify-content: space-around;
}
.container.space-between {  
  justify-content: space-between;
}
<p>Using <code>justify-content: space-around</code>:</p>
<div class="container space-around">
  <div>A</div>
  <div>B</div>
  <div>C</div>
</div>

<hr />

<p>Using <code>justify-content: space-between</code>:</p>
<div class="container space-between">
  <div>A</div>
  <div>B</div>
  <div>C</div>
</div>

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

...