July 20, 2011

Line break with css

Question by winchendonsprings

I have 7 divs in a row with all very little content. I want to have the first 3 one a line then the next 3, and so on.

<div class="parent">
 <div class="child-a">abc</div>
 <div class="child-b">def</div>
 <div class="child-c">ghi</div>
 <div class="child-d">jkl</div>
 <div class="child-e">mno</div>
 <div class="child-f">pqr</div>
 <div class="child-g">stu</div>

So how can I make this work?

For the first line I have

.child-a, .child-b, .child-c {
  padding: 0 2% 0 0;
  display: inline;
  float: left;

What would the css be for child-c, child-d, child-e so that they would be displayed below child-a, child-b, child-c rather than on the same line?

My complete code: http://jsfiddle.net/winchendonsprings/UfswL/11/

Answer by Starx

A better way to go would be something like this.

.parent div { float: left; }
.parent div:nth-child(3n + 1) { clear: left; }

Every element after the third will go to next line. Demo

This is do what you asked the first 3 one a line then the next 3, and so on. efficiently despites some browsers compatiblity issues.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!