Forcing inline-block
Elements on One Line
To get all elements to appear on one line the easiest way is to:
- Set
white-space
property tonowrap
on a parent element that hasoverflow-x: auto
set to show horizontal scrollbars. - Have
display: inline-block
set on all child elements.
For example:
HTML:
<ul id="parent"> <li>Box #1</li> <li>Box #2</li> <li>Box #3</li> </ul>
CSS:
#parent { list-style: none; width: 100%; height: 90px; margin: 0; padding: 0; white-space: nowrap; overflow-x: auto; overflow-y: hidden; } #parent > li { display: inline-block; width: 50%; height: 100%; background-color: red; } #parent > li:nth-child(even) { background-color: blue; }
Please note that:
- The width of the parent and child elements is set in percentage (to make it fluid), this can easily be changed to any other unit of measure, for example using pixels (
px
) for fixed-width horizontally scrollable elements. - Using
display: inline-block
may leave unwanted gaps between elements, read our guide on how to remove the gap between inline-block elements.
Forcing Floated Elements on One Line
This method works by having:
- Three elements: a parent, a child wrapper, and child elements that will be floated.
- A parent element that is used to constrain the children to a set width by setting a fixed-width and
overflow: hidden
to cut-off any overflowing child elements. - A child wrapper element that is set to a width larger than the parent element so that it overflows to allow enough space for the child elements to properly float horizontally on to the same line.
- Child elements that are floated, and have a fixed-width (which does not exceed the child wrapper's width).
For example:
<div id="parent"> <ul id="childWrapper"> <li>Box #1</li> <li>Box #2</li> <li>Box #3</li> </ul> </div>
#parent { width: 300px; height: 90px; background-color: yellow; overflow-x: auto; overflow-y: hidden; } #childWrapper { list-style: none; width: 450px; height: 90px; margin: 0; padding: 0; overflow: hidden; } #childWrapper > li { float: left; width: 150px; height: 90px; background-color: red; } #childWrapper > li:nth-child(even) { background-color: blue; }
Please note that setting percentages on all three, parent, child wrapper and the child elements (li
) may yield unwanted results as each element's width would be calculated with respect to the width of their respective containing blocks. If you want to make fluid boxes then it's best to use the display: inline-block
technique explained earlier.
Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.