Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select only first-level children of an element [closed]

How do I select all the first-level div elements marked below:

<div>
  <a>         //
    <span></span>
  </a>
  <ul>         //
    <li></li>
    <li></li>
  </ul>
  <div>         //
    <div></div>
  </div>
  <span>         //
  </span>
</div>

When I use the wildcard selector it also selects the descendants. I only want the first-level children. How do I do it with css only?

like image 750
m_j_alkarkhi Avatar asked Nov 16 '25 17:11

m_j_alkarkhi


1 Answers

You could go with a CSS reset rule for this issue.

First you set your style as you want it to look on your first level child elements, the you can use a reset rule parentEl -> everything -> everything --> #el > * > * to reset the style back to its default settings. Essentially this says every child element of every child element that is a child of the parent element.

NOTE: Keep in mind that anything you style in the initial first-level of children will need to be reset to its default style within the div > * > * reset rule.

Though this is not needed, you could use the :root to set your default styles as css variables, so you have them all in one area, your root elements properties, and then call them on your reset css properties.

See the following snippit:

:root {
  --def-color: black; 
}

div > * {
  color: red;
}
/* reset rule */
div > * > * {
  color: var(--def-color);
}
<div>
  <a>child level 1    //   
    <span>span child lvl 2</span>
    <div>div child lvl 2</div>
  </a>
  <ul>ul child level 1        //
    <li>li child level 2</li>
    <li>li child level 2</li>
    <li>
      <ul>ul child lvl 3
        <li>li child level 4</li>
      </ul>
    </li>
  </ul>
  <div>child level 1         //
    <div>child level 2
      <div>child level 3</div>
    </div>
  </div>
  <span>child level 1       //
  </span>
</div>
like image 111
dale landry Avatar answered Nov 18 '25 08:11

dale landry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!