2 Column Layouts (Responsive Demos & Example HTML/CSS)

Static 2 Column Layout (Flexbox)

This two-column layout uses flexbox to make the columns stay side-by-side, equal-width, and equal-height even on small mobile screens.

Live demo

1 2

The HTML

<div class="two-columns"> <div>1</div> <div>2</div> </div>

The CSS

/* container */ .two-columns { display:flex; } /* columns */ .two-columns > * { width:50%; padding:1rem; }

The element types used for the container and columns are not specifically referenced in the CSS so you don't have to use divs, you are free to use any kind of element, eg: <article>, <section>, <figure>, or whatever is best for your situation.

I recommend custom elements instead of divs. See why they're so much better in my article: Replace Divs With Custom Elements For Superior Markup.

How to add gutters (column-gap)

Flexbox is smart, you can add gutters between your columns and they will automatically reduce in size to compensate.

However...

If you add a flex-wrap:wrap; declaration on your container, the columns will trip over to multiple lines because they're too wide!

To fix this, we need to explicitly set the correct (narrower) width to each column to allow for the gutters.

Here's an example:

If you have gutters set to 2rem then each column width will be 50% minus 1rem.

/* container */ .two-columns { display:flex; column-gap:2rem; } /* columns */ .two-columns > * { width:calc(50% - 1rem); }

Use the same units in your calc as you do in your column-gap declaration, they can be %, px, em, vw, vh, or whatever works best for your situation.

Từ khóa » Html Css Div 2 Column Layout