What is the best way to choose the topmost parent element that fits a CSS selector criteria?

If I don't know the parent container elements, how can I create a CSS selector that targets only the top-level element(s) without referencing any elements above it? For example, consider the following:

<...>
  <div class="foo">
    foo1
    <div class="foo">foo2</div>
    <span class="foo">foo3</div>
    <div class="bar">
      bar
      <div class="foo">foo4</div>
    </div>
  <div>
</...>

How could one write a CSS selector to target only the outermost "foo" element and not any of the nested ones within it?

I initially attempted .foo:root, but :root does not function in that manner. Neither would .foo:first-child or .foo:first-of-type work, as I am unable to select exclusively from children of a specific element. Are there any other viable solutions?

Answer №1

Choose all elements with the class .foo that do not have a parent element with the same class.

.foo:not(.foo .foo) {
  border: 2px solid gold;
}
<div class="foo">
  foo1
  <div class="foo">foo2</div>
  <div class="foo">foo3</div>
  <div class="bar">
    bar
    <div class="foo">foo4</div>
  </div>
</div>

Edit: Addressing the comment, avoiding repeating selectors for the sake of DRY principle may not be necessary. However, utilizing a nesting selector could lead to something like this:

.foo {
  &:not(& &) {
    border: 2px solid gold;
  }
}
<div class="foo">
  foo1
  <div class="foo">foo2</div>
  <div class="foo">foo3</div>
  <div class="bar">
    bar
    <div class="foo">foo4</div>
  </div>
</div>

You can verify browser support for CSS nesting on caniuse.com. Currently (January 2024), the browser support is quite limited (No safari 16, No Samsung Internet).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to layer multiple navigation menus on top of each other using z-index?

I'm facing a challenge trying to position or overlap two navigation menus in my project. The technologies I am using are Bootstrap, HTML, and CSS. It seems like I might need to utilize the z-index property, but I'm unsure about the exact impleme ...

My navbar is not expanding properly when toggled

I've been struggling to understand bootstrap 4 and the navbar feature is giving me a hard time. I initially managed to get the icon to display correctly, but then I must have made a mistake because now it's not showing up at all. Additionally, I ...

Navbar brand in Bootstrap 4 not centered when navbar is collapsed

I am currently working on aligning the brand-item and nav-items on mobile view. The alignment is incorrect in the mobile view. It is not centered. The "Brand" should be vertically aligned with "link1-3". In the desktop view, the alignment should be like ...

Tips on personalizing Materialize modal components

I am struggling to get the modal to appear on the right side of the screen with a specific width and height. However, it seems to be displaying differently on different screen sizes. For instance, on small screens, only half of the modal is visible while ...

elevate the shadow of the menu bar above the background image

How can I ensure that the drop shadow of the menu appears in front of a background image within a div? See below for my CSS code nav { width:900px; margin: 4px auto 0px 8%; font-size: 16pt; padding-bottom: 0px; -moz-box-shadow: 7px ...

Mastering the correct application of flex properties within nested flex containers

I'm struggling with utilizing flexbox properly and would like some clarification on how nesting parent and child elements functions. I understand that the child elements inherit the parent's flex properties, but I'm unsure if this inheritan ...

Why isn't my CSS transition animation working? Any suggestions on how to troubleshoot and resolve

I am looking to incorporate a transition animation when the image changes, but it seems that the transition is not working as intended. Can anyone provide guidance on how to make the transition style work correctly in this scenario? (Ideally, I would like ...

What is the best way to align the main navigation at the center of

Even though I have utilized text-align: center, the style of .main-nav did not change. What is the most effective way to center this navigation menu? /***** Navigation *****/ .main-nav { font-family: 'Lato', Helvetica, Arial, sans-serif; f ...

sole-child class-based selector

I am trying to target a single div with a specific class using the only-child pseudo-selector. I attempted the following approach: .foo .bar:only-child { background-color: red; } <div class="foo"> <div>1</div> <div class="bar" ...

How to customize the style of a td element in an HTML table

Attempting to modify the style of a td element: .valuator .sw-slots table, tr, td { width 100% } Even after trying to override with this code: td.license-name-td{ width: 100px !important; } The global style always takes precedence over my specific s ...

The column headers in the Kendo grid fail to resize proportionally

The column headers in the Kendo grid do not scale correctly when the browser has a large or small resolution. This issue can be easily reproduced by zooming in or out on the browser. Refer to the image below for an example. Is this a known bug, and are th ...

Utilizing Bootstrap 5: Breaking a Page into Two Separate Vertical Sections

I am looking to design a unique grid system that divides the page into either 2 columns or 2 rows that are completely separate from each other. This means that the content on one side of the page does not expand to match the height of the content on the ot ...

The alignment of Bootstrap text is not in alignment

Hi there, I am pretty new to bootstrap and have been hunting for a solution regarding this specific layout that I want to achieve. Check out the image below: https://i.sstatic.net/qqaCo.png The issue I am facing is that in my code, the name, code, status, ...

Placing a div within a 960 grid system can sometimes result in unexpected spacing

Testing on various browsers: Chrome, IE, Firefox. I'm facing an issue where the BusinessNav ID keeps getting pushed over 3 columns. Desired page layout can be found here I could definitely hack this code to adjust the positioning. However, with so m ...

Position divs to align text beside icons

I am currently working on a Bootstrap popover to display various pieces of information, each containing an icon and some text. Additionally, I am incorporating twig into this project. Here is the HTML structure: <span class="fa fa-user instructor-con ...

What steps should I follow to align these unordered lists side by side?

Is there a way to align these lists (unordered lists inside list items 1 through 4) side by side using CSS3? I've tried different methods, but I can't seem to figure it out. Here is the code I've been using: <footer> <ul> ...

Div adjusts its height to match another div's, regardless of the latter's size

I'm currently working on a website where I have a list of news displayed in divs. Each div contains two inner divs: an image on the left and the title, date, and the first 30 words of the news on the right. I am looking to make the image div adjust it ...

The user can witness the appearance of a scrollbar when utilizing the

Struggling to remove the scroll bar from my ion-scroll. Have tried various methods but nothing seems to work. Need assistance with this, please! Attempted using all attributes and even used CSS like ::-webkit-scrollbar with display: none;, which hides it ...

Restricting zooming to only occur within the img element in a UI

Is there a method to enable image zoom inside specific divs without affecting the overall page zoom? At the moment, I have: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale ...

Customizing the default framework design

Is there a way to modify the default scaffolding using CSS so that both the label and the editor appear on the same line, with the label column having a fixed width? <div class="editor-label"> @Html.LabelFor(model => model.Price) ...