A few days ago I wrote a post entitled “Floating Divs in a Div” where I shared a small quirk I was having with the float property when I coding a layout that had nested divs inside a larger div. After another post where I learned that ‘inline-block’ acts almost just like ‘float’ I wanted to go back and revisit to see if I would have the same issue.
Here is the premise: I want to code 3 divs, each with a pink dotted border, and have the line up on a horizontal line (side by side) within a larger blue div. To achieve this in the earlier post I had to use the ‘float: left’ property in the CSS for the pink bordered divs and ‘overflow: auto’ for the outer blue div. The code looked like this:
CSS:
.outside-div {border: 2px solid blue; width: 400px; padding: 15px; overflow: auto;}
.inside-div {border: 3px dotted pink; width: 90px; margin: 2px; float: left;}
HTML:
<div class=”outside-div”>
<div class=”inside-div”>Learn HTML</div>
<div class=”inside-div”>Learn CSS</div>
<div class=”inside-div”>Learn JavaScript</div>
</div>
Now let’s check to see if ‘inline-block’ still requires me to add the ‘overflow-auto’ property to the outer blue div.
CSS:
.outside-div {border: 2px solid blue; width: 400px; padding: 15px; overflow: auto;}
.inside-div {border: 3px dotted pink; width: 90px; margin: 2px; float: left; display: inline-block;}
Wow, inline-block worked perfectly fine for this! Also, note that it requires less code! I’ll have to keep this in mind next time I think about using ‘float.’ You can view the results here.
Note: I don’t think that inline-block can act as a replacement for float in all scenarios. Inline-block appears to only align to the left, with float you can float an element left and right. There may be more differences between the two but that is the one that immediately stuck out to me.
