Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Even distribute divs with a fixed size

Tags:

html

css

I went through a couple of similar questions but the answers didn't work for me.

I have several divs, and each of them has a fixed width of 210px.

The container they're in can resize depending on the screen size of the user. The divs have to be evenly spaced horizontally at all time and it should also break the line of divs into another line if there is no space.

To clear things up more, refer the figure below. enter image description here

This JS fiddle has achieved the outcome I want. But I can't see how it'll work for my divs which must have a fixed width.

width: calc(100% / 6);

EDIT:

The problem with the JS Fiddle is that when the screen size is where it has space, but not enough space to fit another div. In which case, the last div should be closer to the right.

enter image description here

like image 910
user3607282 Avatar asked Apr 26 '16 12:04

user3607282


People also ask

How do you evenly distribute items in CSS?

The "space-evenly" value for the justify-content property distributes the space between items evenly. It is similar to space-around but provides equal instead of half-sized space on the edges. Can be used in both CSS flexbox & grid.

How do you put a space in a div in HTML?

Pure HTML: <div></div>&nbsp;&nbsp;&nbsp; Note that &nbsp; represents a single space, so keep adding them until you have enough.


1 Answers

Flexbox can do what you want by setting justify-content to space-around (or space-between, depending on your presentational needs). Here's a quick example:

body{
  display:flex;
  flex-wrap:wrap;
  justify-content:space-around;
  margin:0;
  padding:5px;
}
div{
  background:#000;
  flex:0 0 210px;
  height:210px;
  margin:5px;
  width:210px;
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

Check caniuse.com for details on browser support and prefixing.

like image 91
Shaggy Avatar answered Oct 04 '22 13:10

Shaggy