CSS - How to get rid of empty vertical space with float

When you float, the next floats will take up at least the same amount of vertical space or more before breaking the line and going down in the flow. The image below has a lot of unused white space.

with empty vertical space

How can I get something else like this?

without empty vertical space

Here is a violin. http://jsfiddle.net/BamBamm/4x51qLt4/1/

<div class="someBlock">...</div>
<div class="someBlock">...</div>
<div class="someBlock">...</div>
<div class="someBlock">...</div>

.someBlock {
    display: inline-block;
    vertical-align:top;
    width: 30%;
    float: left;
}

      

((Images copied here: http://designshack.net/articles/css/everything-you-never-knew-about-css-floats/ ))

+3


source to share


4 answers


You can't achieve 100% browser compatibility with pure CSS or perfect top alignment, without js. You can use a library called masonry: http://masonry.desandro.com/ . I am not promoting it, just trying to give you an easy and very pleasant solution to your problem.



+2


source


There's a hack there to fill in the gap, add this:

.someBlock{
    margin-bottom: -100%;
    padding-bottom: 100%;
    overflow: hidden;
}

      



Check this out: JSFiddle

Although I would recommend using something like jQuery Masonry, as Hachem Colami pointed out in the comments.

+2


source


As Hashem Kolami said, what you are trying to accomplish is not possible with CSS. You need to calculate the heights of the various blocks.

But, if it helps you, there is an easy way to make sure that there are a certain number of elements on each line:

.someBlock:nth-of-type(3n+1) {
    clear : both;
}

      

This won't answer your question, but maybe it helps others.

+1


source


If the order of the div is not important, you can use the css3 columns property like this:

body {
     -webkit-column-count: 3;  -webkit-column-gap: 15px; /* Chrome, Safari 3 */
     -moz-column-count: 3;     -moz-column-gap: 15px; /* Firefox 3.5+ */
          column-count: 3;          column-gap: 15px; /* Opera 11+ */
}

      

Demo: http://jsfiddle.net/ytf66xm7/ (you can see that it will fill from top to bottom, not left to right)

If you want left-to-right layout, the only way to solve it is to use JS like Masonry or Salvattore, just like Hashem Qolami said in the comment above.

+1


source







All Articles