How to Use FlexBox and the CSS :nth-child Property

css logo.png

In this brief lesson I will show you how you can use the CSS :nth-child property. This is one property that I often overlook but one which can be put to really good use.

In this example I have a div with a width of 400px and within this main div I have placed 8 smaller div, each with a width of 50px.

What I would like to do is to color each even div with a background color of black. There are a number of ways this can be achieved.

Let us start with a basic page structure with the main div at Lines 11 to 13 as follows:

Note that I have also linked the stylesheet style.css to this page (see Line 8.

The next thing is to generate the 8 divs that I wish to place into the main div. Using PHP this can be achieved quite easily:

Line 13: we use a for loop to echo out the 8 divs

The last step is to style the output:

Line 2: we declare that we are using Flexbox

Line 3: a 1 pixel solid black border is drawn around the main div

Line 4: the flex-wrap property is set to wrap. Note that in this case it will not be required as we have a fixed width but I do like to get into the habit of using it.

Line 5: the flex direction is set to row. This means that our divs will be displayed horizontally. If we wanted to display the divs vertically then we would use flex-direction: column.

Lines 9 to 12: we give a fixed height and width to each div contained within the main div.

Lines 14 to 16: this is where we set the nth-child property. In this case we are declaring that each even numbered div should be colored black.

That’s it. You should now see a black and white grid within a single row.

If you are interested in developing your coding skills then you should take a look at the full courses. Every line of code is explained in much more detail than here.