Skip to main content
Known Participant
May 10, 2017 1:40 PM UTC
Answered

:first-child explained

I have been messing around with a mobile responsive navigation menu from w3schools... How To Create a Responsive Top Navigation Menu

In the sample code they provide, it hides all links apart from the first one, "Home" when the screen is less than 600px...

/* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */

@media screen and (max-width: 600px) {

  .topnav a:not(:first-child) {display: none;}

  .topnav a.icon {

    float: right;

    display: block;

  }

}

I'd rather the menu show another specific link when less than 600px, but I am unsure how to use the first-child. I have done a bit of research on it, but every article just leads to more complication.

Does anyone know where I can obtain easy reading material on this?

This topic is closed to new replies. Start a new post to keep the conversation going.
pziecina
pziecinaCorrect answer
Legend
May 10, 2017 2:53 PM UTC

first child is exactly what it says, the first child item as it is desplayed in the dom, (use the Dw dom panel).

To display a different item and hide all others, use nth-of-type()

see - https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type

3 replies

pziecina
pziecinaCorrect answer
Legend
May 10, 2017 2:53 PM UTC

first child is exactly what it says, the first child item as it is desplayed in the dom, (use the Dw dom panel).

To display a different item and hide all others, use nth-of-type()

see - https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type

Translate
Known Participant
May 10, 2017 3:07 PM UTC

Ah, that article makes more sense. So, nth-of-type then number of element in ()

Thanks pziecina

Translate
pziecina
Legend
May 10, 2017 3:29 PM UTC

Just to be clear, you could use first child, but when you revisit the css code at some point in the future, i have found that the use of nth-of-type makes what you are doing and targeting with the code much clearer.

I only ever use first or last child, when i am targeting the first of last child item, and most css coders i know and examples i have seen used do the same.

Translate