Home > Enterprise >  How to use a single CSS class to modify the styling of multiple elements?
How to use a single CSS class to modify the styling of multiple elements?

Time:04-22

I have a div element that uses a class. The purpose of the class is to

  1. apply CSS to all elements nested in the div
  2. apply CSS to specific elements in the div

How can I achieve this given the following snippet?

/* Need to apply this to ALL elements nested in the class */
.wrapper {
    display: inline; 
}

/* Need to apply this to ONLY <ul> elements nested in the class */
.wrapper ul {
    list-style-type: none;
    margin: 0; 
    padding: 0;   
}
<body>
 <div class='wrapper'>
   <h1>child one</h1>
   <ul>
      <li>child two</li>
      <li>child three</li>
      <li>child four</li>
   </ul>
 </div>
</body>

I am aware of CSS selectors. In this case, I could potentially use selectors for elements in the div that need to be handled separately; however, is there another way of doing this rather than having to write a selector for each HTML element?

CodePudding user response:

.wrapper * {
    display: inline; 
}

So what .wrapper * is telling is us to select any selector (* being the wildcard) that's nested in the .wrapper class.

If you want to recursively select ul elements inside of the .wrapper, you can just use what you already have. However, if you want only ul elements that are direct children of the div, you can use the .wrapper > ul selector.

CodePudding user response:

You can also use .wrapper *:first-child to get the first element nestled inside the parent element.

  • Related