David Powell David Powell - 5 months ago 9
CSS Question

how to align divs with different width within another parent div?

This image will explain what I mean:

What I want

There is a transparent div that contains all the other small dark gray divs which has the dummy text in red ,

I set the parent div to

width:80%;
height:100%;
margin: auto;
padding:0 0 0px;


and the child divs are not consistent in width their width change depending on the length of the text inside here is the CSS

float:left;
width:auto;
height:1.5em;
display: inline-block;


Now when new child divs are created they start perfectly aligned from the left hand side of the parent div, however on the right hand side they are not aligned at all to the end of the parent div (as in the image) they look messy. How to do that, is it possible with only CSS or Javascript will be needed ?

<div id="parent"><span class="child"></span></div>

Answer

Aside from the Flex-box solution already mentioned you can simply use text-align:justify on the parent container like so:

.container {
  background: #333;
  padding: 14px;
  font-size:0;
  text-align:justify;
}
.container div {
  display:inline-block;
  margin:4px;
  background: #111;
  border-radius: 3px;
  padding: 5px;
  line-height: 1em;
  color: red;
  font-size:16px;
}
<div class="container">
  <div>Maecenas faucibus</div>
  <div>mollis</div>
  <div>interdum</div>
  <div>Nullam</div>
  <div>id</div>
  <div>dolor</div>
  <div>id nibh ultricies</div>
  <div>vehicula</div>
  <div>ut</div>
  <div>id</div>
  <div>elit</div>
  <div>mollis</div>
  <div>interdum</div>
  <div>Nullam</div>
  <div>id</div>
  <div>dolor</div>
  <div>faucibus</div>
  <div>id nibh ultricies</div>
  <div>vehicula</div>
  <div>ut id</div>
  <div>elit</div>
  <div>dolor</div>
  <div>id nibh ultricies</div>
  <div>vehicula ut</div>
  <div>mollis</div>
  <div>interdum</div>
  <div>Nullam</div>
  <div>id</div>
  <div>dolor</div>
  <div>faucibus</div>
  <div>id nibh ultricies</div>
  <div>vehicula</div>
  <div>ut id elit</div>
</div>

Its worth noting that unlike flex-box's justify-content: space-between the text-align:justify property won't justify the final row.