简体   繁体   中英

CSS/JS: Evenly spreading elements across multiple lines

How would you go about evenly spreading elements across multiple lines, for example:


wrapper div: <div style="text-align: center">
elements inside: <div style="display: inline-block;
                 padding-left: 10px; padding-right: 10px;">Element</div>

Instead of only having one element on the next line (wrapped):

Element 1        Element 2        Element 3        Element 4        Element 5
                          Element 6

It does this, spreading out the elements:

Element 1        Element 2        Element 3
Element 4        Element 5        Element 6

If the width of the elements and their count is not fixed, I would write a code which generates custom markup depending on the situation.

However it may get tricky because with the web medium, it's hard (impossible actually) to calculate the actual size in pixels of a text block (no way of knowing what font will a browser use and get its metrics).

I'd suggest deciding on the number of columns in advance (2 or 3) then using elements with their width set to 50% or 33% and text-align property to center .

如何指定“宽度”样式?

<div style="width: 50px; display: inline-block; padding-left: 10px; padding-right: 10px;">Element</div>

Float them all left, width to 50% or 33% or whatever you need.

Make sure you clear the float afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM