-2

This is what I have:
I have a div id="navbar" and various styles for the ul and li elements there.

Now I want to know, if there is any selector in CSS where I can say "the following css-styles shall only be aplliedd to children of #navbar"

something like:

/* ***** NAVBAR ****** */
#navbar {
    /* Add a gray right border to all list items, except the last item (last-child) */
    li {
        border-right: 1px solid #bbb;
    }

    li:last-child {
        border-right: none;
    }

    .active {
        background-color: #4CAF50;
    }

    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #333;
    }

    li {
        float: left;
    }

    li a {
        display: block;
        color: white;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
    }
    /* Change the link color to #111 (black) on hover */
    li a:hover {
        background-color: #111;
    }
}

are there any ways to apply various css-styles only to elements that are chil or child-child or child-..-child of a certain HTML-element?

Note I'm also using jQuery so if thats only possible with jQuery, it will not be a problem.

sincerly basti

Martijn
  • 15,791
  • 4
  • 36
  • 68
Sebastian Röher
  • 417
  • 7
  • 20
  • 1
    `#example > * {}` will select only direct children – Martijn Feb 15 '18 at 08:11
  • 1
    The answer will be different if you mean ALL Children (in all levels), or only the next level of children. @Martijn has given the best answer I believe. – Lee Feb 15 '18 at 08:13
  • @Lee: *"...only to elements that are chil or child-child or child-..-child of a certain HTML-element?"* Clearly the OP is referring to descendants, not direct children. – T.J. Crowder Feb 15 '18 at 08:14
  • @T.J.Crowder fair enough – Lee Feb 15 '18 at 08:16
  • i guess a very tiny small search looking about CSS selector and you will end up with the answer – Temani Afif Feb 15 '18 at 08:16

2 Answers2

3

You're looking for the descendant combinator: A space. For instance:

#navbar li {
    /* styles */
}

That will only apply the styles to li elements that are descendants of #navbar.

You have to use it on every rule. If you want syntax more like what you have in your question, there are preprocessors that do that sort of thing: Sass, Less, and such.

But with just CSS itself, you need to repeat the #navbar on every rule.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Direct Children

#parent > #child {
    color: #fff;
}

Descendants

#parent #descendant {
    color: #fff;
}
Cristian S.
  • 937
  • 5
  • 13