Casey
Casey

Reputation: 105

How do I target a child of a specific class?

so I'm trying to target only the top level list items that are direct children from the ol with the class foo. I want to make them red.

ol.foo>li {
  color: red;
}
<html>

<head>
  <title>test</title>
  <link href="index.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <ol class='foo'>
    <li>section 1</li>
    <li>section 2
      <ol>
        <li>step 1</li>
        <li>step 2</li>
        <li>step 3</li>
      </ol>
    </li>
    <li>section 3</li>
    <li>section 4</li>
  </ol>
  <ol>
    <li>item 1</li>
    <li>item 2</li>
  </ol>
</body>

</html>

Upvotes: 0

Views: 61

Answers (3)

fjoe
fjoe

Reputation: 1160

The color for your first li is getting inherited to other list items.

The other answers here are using the color black to fix this.

Here is a solution that allows you to get the desired affect without having to define another color.

ol.foo li {
  color: initial;
}

ol.foo > li {
  color: red;
}
<html>

<head>
  <title>test</title>
  <link href="index.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <ol class='foo'>
    <li>section 1</li>
    <li>section 2
      <ol>
        <li>step 1</li>
        <li>step 2</li>
        <li>step 3</li>
      </ol>
    </li>
    <li>section 3</li>
    <li>section 4</li>
  </ol>
  <ol>
    <li>item 1</li>
    <li>item 2</li>
  </ol>
</body>

</html>

Upvotes: 3

mtr.web
mtr.web

Reputation: 1525

You will probably have to add a second selector to change it back because there isn't a preexisting rule dictating the color:

ol.foo>li {
  color: red;
}
ol.foo > li ol li {
  color: black;
}

Upvotes: 0

Sanchit Patiyal
Sanchit Patiyal

Reputation: 4920

One way of doing it

ol.foo>li {
  color: red;
}

ol.foo>li>ol{
  color: black;
}
<html>

<head>
  <title>test</title>
  <link href="index.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <ol class='foo'>
    <li>section 1</li>
    <li>section 2
      <ol>
        <li>step 1</li>
        <li>step 2</li>
        <li>step 3</li>
      </ol>
    </li>
    <li>section 3</li>
    <li>section 4</li>
  </ol>
  <ol>
    <li>item 1</li>
    <li>item 2</li>
  </ol>
</body>

</html>

Upvotes: 1

Related Questions