1. The background

For layouts with multiple elements on the same row, it is common to use round-robin:

There is also the secondary classification menu:

  • Example a

  • Example 2

Here’s how I’ll explore this layout: First, agree the HTML result:

div.wrap
	div.row
	  div.col
	  div.col
	  div.col
  ...
Copy the code

2. Calculate the width

Set the width of div. Row to the width of div. Col * the number of div. Col, and then set div. Col to float:left or display:inline-block

2.1 floatsolution

For float:left, div.row needs to clear the float.

  • Advantages: good compatibility, no need to cleardiv.colDirect clearance, because floating elements are always aligned with the top of the current line box, vertical-align does not work.
  • Disadvantages: The width of div.row is computed.

2.2 inline-blocksolution

For display:inline-block, either compress the HTML or set font size:0 for div.row to remove the horizontal gap between div.col, which also incidentally removes the vertical gap. The final value is line-height *font size). For the former, we can set vertical-align:top for div. Col or line-height:0 for div. Row. The former (vertical-align) is recommended because div. Col is aligned at the top when the height is not equal, but you can also bottom or middle.

Of course, if there are inline elements or inline-block elements in div. Col, they inherit the font size and line-height of the parent element, so you need to reset the font size and line-height to override the values corresponding to div. Row.

3. white-space:nowrap

*{ margin: 0; padding: 0; } .wrap { width: 200px; height: 100px; overflow-x: auto; overflow-y: hidden; } .row{ white-space: nowrap; Background-color: RGB (0,0,0); background-color: RGB (0,0,0); Font-size: 0; // Remove horizontal + vertical clearance}. Col {display: inline-block; *display: inline; // Compatible with IE 6/7, analog inline-block effect *zoom: 1; // Compatible with IE 6/7, simulate inline-block effect width: 20px; margin-right: 30px; height: 100px; background-color: red; font-size: 14px; Font-size vertical-align: top; // Align up while removing the vertical gap}Copy the code

The black background is div.row and the red background is div.col.

You can see that this is the same as a text container with white-space: Nowrap applied.

The advantage of approach 2: compatibility (IE5 is normal), no need to calculate the width, can be arbitrary multiple div.col, and the width of div.row is equal to the width of its parent element.