Tomoro Logo

Alternating Left/Right Layouts with Pure CSS

I've been using Pure CSS for awhile now, I love its minimal footprint and percentage/fraction based widths. On a recent design I needed create a layout where an image would appear to the left on one row, then to the right on the next row. Without changing the HTML for every alternating row.

Usually I would've used floats for the image, alternating left and right. But floats are awful for layout, so here's a smarter way.

View this on Code Pen.

Here's the HTML:

Image
Article
Image
Article
Image
Article

…and here's the CSS:

@import url("http://yui.yahooapis.com/pure/0.6.0/pure-min.css");

* {
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	box-sizing: border-box;
}

section:nth-of-type(even) {
	direction: rtl;
}

section>* {
	direction: ltr;
}

figure {
	background: #55EEFF;
	height: 100px;
	margin: 0;
}

article {
	background: #44AAEE;
	height: 100px;
}

figure,
article {
	padding: 1em;
}

Explanation

Notice how in the HTML we're marking up the image first, article second. So without any CSS the image will always appear first.

1. In the CSS we're first importing all the styles from Pure, so that our grids work. Next I've added border-box sizing because it rocks.

2. Next we're saying for every second (even numbered) Section, change the text direction to right-to-left. Because Pure makes all grid elements inline-blocks, text direction will determine in what order the elements will be displayed.

3. Lastly we're saying any direct descendant of a Section should read left-to-right, this stops the text in each box from reading backwards.

The rest of the styles are all just for demonstration purposes.

Hope you found this useful!