Press enter to go to start of page

Cascading Stylesheets

Child Elements

Learning Outcomes

On completion of this lesson you will know how to identify child elements from their position within the parent element

Go to top

Introduction

Paraphrasing the rhyme above we could say that great container elements have little container elements repeating themselves inside them while little container elements have lesser container elements but not to infinitum.

To put this in the context of HTML the <html> element has the lesser elements <head> and <body> inside it. The <body> element itself has the lesser still <header>, <main> and <footer> inside it.

In the next level down main itself can have any combination of <article>, <section>, <aside>, <figure> etc inside of it. Each of those elements can have repetition of other elements inside them. However if you go down more than three move levels, it is time to rethink the design of your page.

Go to top

first-child/last-child

In Listing 1 below the <body> contains one <article> which has six <section> inside it, each containing a poem or an extract from a play. At fist we shall look at those as formatted all with the same style and then we shall look at how we would give a special formatting to the first and last poem.

Listing 1
                        <!DOCTYPE html>
                        <html lang="en">
                            <head>
                                <link href="Poems.css" rel="stylesheet" type="text/css">
                                <title>Poetry</title>
                                <meta charset="utf-8">
                            </head>
                            <body>
                                <header>
                                    <h1>Poems and Play Extracts</h1>
                                </header>
                                <main>
                                    <h2>Skakespeare, Barret-Browning and Wordsworth</h2>
                                    <article>
                                        <section>
                                            <p>Shall I compare thee to a summer’s day?<br>
                                            Thou art more lovely and more temperate.<br>
                                            Rough winds do shake the darling buds of May,<br>
                                            And summer’s lease hath all too short a date.<br>
                                            Sometime too hot the eye of heaven shines,<br>
                                            And often is his gold complexion dimmed;<br>
                                            And every fair from fair sometime declines,<br>
                                            By chance, or nature’s changing course, untrimmed;<br>
                                            But thy eternal summer shall not fade,<br>
                                            Nor lose possession of that fair thou ow’st,<br>
                                            Nor shall death brag thou wand'rest in his shade,<br>
                                            When in eternal lines to Time thou grow'st.<br>
                                                So long as men can breathe, or eyes can see,<br>
                                                So long lives this, and this gives life to thee.</p>
                                        </section>
                                        <section>
                                            <p>How do I love thee? Let me count the ways.<br>
                                            I love thee to the depth and breadth and height<br>
                                            My soul can reach, when feeling out of sight<br>
                                            For the ends of being and ideal grace.<br>
                                            I love thee to the level of every day's<br>
                                            Most quiet need, by sun and candle-light.<br>
                                            I love thee freely, as men strive for right.<br>
                                            I love thee purely, as they turn from praise.<br>
                                            I love thee with the passion put to use<br>
                                            In my old griefs, and with my childhood's faith.<br>
                                            I love thee with a love I seemed to lose<br>
                                            With my lost saints. I love thee with the breath,<br>
                                            Smiles, tears, of all my life; and, if God choose,<br>
                                            I shall but love thee better after death.</p>
                                        </section>
                                        <section>
                                            <p>I wandered lonely as a cloud<br>
                                            That floats on high o'er vales and hills,<br>
                                            When all at once I saw a crowd,<br>
                                            A host, of golden daffodils;<br>
                                            Beside the lake, beneath the trees,<br>
                                            Fluttering and dancing in the breeze.</p>
                                        </section>
                                        <section>
                                        <p>I know a bank where the wild thyme blows,<br>
                                            Where oxlips and the nodding violet grows,<br>
                                            Quite over-canopied with luscious woodbine,<br>
                                            With sweet musk-roses and with eglantine:<br>
                                            There sleeps Titania sometime of the night, <br>
                                            Lulled in these flowers with dances and delight.</p>
                                        </section>
                                        <section>
                                            <p>Things base and vile, folding no quantity,<br>
                                            Love can transpose to form and dignity:<br>
                                            Love looks not with the eyes, but with the mind;<br>
                                            And therefore is wing'd Cupid painted blind:<br>
                                            Nor hath Love's mind of any judgement taste;<br>
                                            Wings and no eyes figure unheedy haste:<br>
                                            And therefore is Love said to be a child,<br>
                                            Because in choice he is so oft beguiled.</p>
                                        </section>
                                        <section>
                                            <p>As love is full of unbefitting strains,<br>
                                            All wanton as a child, skipping and vain,<br>
                                            Form'd by the eye and therefore, like the eye,<br>
                                            Full of strange shapes, of habits and of forms,<br>
                                            Varying in subjects as the eye doth roll<br>
                                            To every varied object in his glance</p>
                                        </section>
                                    </article>
                                </main>
                                <footer>
                                </footer>
                            </body>
                        </html>
                    

six poems each formatted similar to the others
Fig 1

Fig 1 is a screenshot of Listing 1 with styling according to lines 1 to 47 from Listing 2. If you compare this with the contents of Listing 1 itself you can see that the poems are sequenced in the same order in both cases, with a left to right sequence and moving to the next line when they run out of space.

As there is nothing new in Lines 1 to 47 of Listing 2, we won't comment on them further and instead we shall look at lines 48 to 53, where we introduce our first-child and last-child pseudo classes.

Listing 2
                        html{
                            font-size: 75%;
                            background-color: #eee;
                        }
                        header, main, footer{
                            width: 100%;
                            max-width: 900px;
                            min-width: 500px;
                            margin: 0 auto;
                            padding: 10px
                        }
                        header{
                            background-color: #008;
                            color: beige;
                            border-top-right-radius: 25px;
                            border-top-left-radius: 25px;
                        }
                        main{
                            background-color: antiquewhite;
                        }
                        footer{
                            background-color: #444;
                            border-bottom-right-radius: 25px;
                            border-bottom-left-radius: 25px;
                        }
                        footer p{
                            color: white;
                        }
                        footer p a{
                            color: yellow;
                        }
                        h1, h2{
                            text-align: center;
                        }
                        h1{font-size: 2rem}
                        h2{font-size: 1.5rem}
                        section{
                            border:medium solid blueviolet;
                            background-color: beige;
                            margin:3px;
                            color: #448;
                            font-size: 1rem;
                            font-weight: bold;
                            padding-left: 10px;
                            width: 400px;
                            display:inline-flex;
                        }
                        article section:first-child, article section:last-child{
                            background-color: blueviolet;
                            border:medium solid #448;
                            color: beige;
                            text-shadow: 1px 1px 2px black;
                        }
                    

In Listing 1 the article element spans lines 14 to 81. Inside this are six section elements. These section elements are referred to as child elements of the article element. The order of those child elements is determined by their appearance in the HTML file. Thus, referring to Listing 1 above, the first section element spans lines 15 to 30 while the second element spans lines 31 to 46. The last child element spans lines 73 to 80. Form this we deduce the first-child element spans lines 15 to 30 while the last child element spans lines 73 to 80.

Those are the two elements that are targeted by lines 48 to 53 of Listing 2. The pseudo classes first-child and last-child identify them solely on the basis of their positions in the list of section blocks.

The styling applied to those two child elements in Lines 48 to 53 of Listing 2 is quite simple and therefore there is no need to explain it.

six poems with the first and last formatted differently to the others
Fig 2

Fig 2 above shows the list of poems with the first and last poem styled differently to the rest.

Before we leave this example it is worth stating that there is nothing special about the two poems that are styled differently to the rest, just that they were in the first and last positions respectively inside the article block. If we were to add another poem before the current first one and another after the last one, the two newly added poems would take on the identities of first-child and last-child For this reason the two newly added poems would have the special styling applied to them and the two who are currently styled like that would return to normal formatting.

Go to top

nth child

We have just looked at how to identify the first and last element in a group of elements within a container element. We are not, however, limited to identifying elements from the two extremeties of a group. Here we are looking at being able to identify elements within a group depending on whether they are in an odd or even position. This allows us to be able to colour odd and even positioned elements differently. This is useful for presenting a long lits since alternate lines being colured differently makes the list easier to read.

For our example here, however, we shall use a list of very short paragraphs where the odd positioned paragraphs are colured blue and the even ones coloured yellow.

Listing 3
                        <!DOCTYPE html>
                        <html lang="en">
                            <head>
                                <link href="enth%20child.css" rel="stylesheet" type="text/css">
                            </head>
                            <body>   
                                <main>
                                   <article>
                                       <p>I am the first paragraph and I am odd</p>
                                       <p>I am the second paragraph and I am even</p>
                                       <p>I am the third paragraph and I am odd</p>
                                       <p>I am the fourth paragraph and I am even</p>
                                       <p>I am the fifth paragraph and I am odd</p>
                                       <p>I am the sixth paragraph and I am even</p>
                                       <p>I am the seventh paragraph and I am odd</p>
                                       <p>I am the eighth paragraph and I am even</p>
                                       <p>I am the ninth paragraph and I am odd</p>
                                       <p>I am the tenth paragraph and I am even</p>
                                       <p>I am the eleventh paragraph and I am odd</p>
                                       <p>I am the twelfth paragraph and I am even</p>
                                    </article>
                                </main>
                                <footer>
                                </footer>
                            </body>
                        </html>
                    

Above is our HTML code. I don't think any explanation is required for it. It simply displays twelve paragraphs, each one announcing its position in the list and whether it is odd or even.

six poems with the first and last formatted differently to the others
Fig 3
Listing 4
                        main{
                            width:400px;
                            margin: 0 auto;
                            background: antiquewhite;
                            padding: 10px;
                        }
                        p{
                            padding: 7px;
                            margin: 0;
                        }
                        p:nth-child(2n+1){
                            background-color:aqua;
                        }
                        p:nth-child(2n){
                            background-color:#ffa;
                        }

                    

In Listing 4 above, if we were to use only lines 1 to 10 then our page would look like Fig 4 above - not very inspiring. Lines 11 to 16 will, however, take care of that.

At line 11 we meet our first pseudo class: :nth-child(n+1). If you are familiar with algebra then you will know that as long as n is an integer the expression 2n + 1 will always be an odd numbe. Thus lines 11 is targeting the odd numbered lines.

Line 12 tells us that the background colour of the target will be aqua, in othe words a bright blue.

At line 14 we meet the pseudo class :nth-child(2n). Again, as long as n is an integer 2n will always be an even number. Thus line 14 is targeting the even lines. Line 15 changes the background colour of those to #ffa, which is a bright yellow.

six poems with the first and last formatted differently to the others
Fig 4

Fig 4 above shows the alternating blue and yellow lines.

Go to top

Summary

In this lesson we have looked at two means of identifying child elemnts within a container element:

Click on this link for more information on the :nth-child() pseudo class.

Go to top

Exercise

  1. Copy the code in Listing 1 into an HTML editor, then link it to a CSS file that will style even positioned poems with a yellow background and the odd positioned ones with an orange background. Of course you may pick any other colurs you wish or use different styles or text or borders etc.
  2. Copy the code in Listing 3 into an HTML editor. To give yourself space for the next part add at least another 12 paragraphs inside the article block. Next find more information from the :nth-child() pseudo class link. Using information from this link create a CSS file that will apply styling to every third, every fourth or fifth paragraph.
Go to top