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">2</div>
  <div>3</div>
</div>

Unfortunately, this method did not yield the desired result. Is it possible to use only-child with classes or is it restricted to HTML element types?

Solution:

After some exploration, I discovered a solution. Even though it was flagged as a duplicate (which I disagree with), I will share it here:

.foo bar:only-of-type {
  background-color: red;
}
<div class="foo">
  <div>1</div>
  <bar>2</bar>
  <div>3</div>
</div>

Answer №1

Currently, it appears that only Safari has support for nth-child when specifying a class (not just the tag name).

This code snippet targets a specific div with the class "bar" in Safari (tested on IOS) but not in Edge/Chrome (Windows10). More information can be found on caniuse.com.

.foo div[class="bar"]:nth-child(1 of .bar):nth-last-child(1 of .bar) {
  background-color: red;
}
<div class="foo">
  <div>1</div>
  <div class="bar">2</div>
  <div>3</div>
</div>

Answer №2

:only-child targets the specific element that is the only child of its parent (meaning it has no siblings). For example, if we have the selector .foo .bar:only-child, it would match the following HTML structure:

<div>
    <div class="foo bar"></div>  
</div>

It seems like the HTML you provided does not contain any only children. If you are looking to target a child element directly under a parent, you may want to use a different selector like .foo > .bar.

Answer №3

It doesn't appear to be achievable using the only-child selector. However, you can utilize the > combinator to specifically target the class .bar among the child elements.

.foo > div.bar {
  color: red;
}
<div class="foo">
  <div>1</div>
  <div class="bar">2</div>
  <div>3</div>
</div>

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

Should buttons be wrapped based on the text of the link?

I'm struggling to include buttons in my design but I can't seem to achieve the desired outcome. The image below illustrates what I am attempting to create but have been unsuccessful in replicating: https://i.sstatic.net/CnYLV.png However, the ...

Tips for including information in a chart

I'm facing an issue with my current code as it is not functioning properly. Here is the link to the current output: http://jsfiddle.net/4GP2h/50/ ...

How to create a transparent background image in a Jekyll theme without impacting the visibility of the foreground

I'm new to HTML and CSS, currently working with a Jekyll boostrap landing theme from GitHub to create a static responsive website. I'm looking to change the background image on the theme and make it transparent to enhance the visibility of the fo ...

An instructional guide on seamlessly incorporating a TypeScript variable into an HTML element submission method

A problem arises in my Angular 8/Django 3 app as I attempt to incorporate a server-side variable called client_secret into the stripe.confirmCardPayment() method. The error message that keeps popping up is Property 'client_secret' does not exist ...

How can I extract a specific portion of HTML content using C#?

I am working on a page where I need to extract a substring using the following code: static string GetBetween(string message, string start, string end) { int startIndex = message.IndexOf(start) + start.Length; int stopIndex ...

Versatile accordion with separate functionalities for items and panels

When I have different functions for clicking on item and title, clicking on the item works fine but clicking on the panel triggers both functions. Is there a way to resolve this so that I can click on the item using Function_1 and click on the panel using ...

Modify the alignment and orientation of the data within RadHtmlChart

I have a chart: <telerik:RadHtmlChart ID="chrtInvestmentAmount" runat="server" Transitions="true" DataSourceID="SqlDataSource1" Height="256px" Skin="Glow" Width="1024px" RenderMode="Auto"> <PlotArea> <Series> ...

Jumping Sticky Table Headers

Looking for a solution to prevent the table header from moving when scrolling through the data: tbody { overflow-y: scroll; } thead, tbody tr { display: table; width: 100%; table-layout: fixed; text-align: left; } thead, th { position: sti ...

Node JS server fails to load CSS even with the use of express.static

It's quite absurd, but I've been grappling with a rather nonsensical code conundrum for days now. I just can't seem to get the CSS and image to load on my Node.js server. I've tried various solutions (like express.static, etc.), but n ...

Customizing Ngx-bootstrap Carousel Indicator, Previous, and Next Button Styles

<carousel > <a href=""> <slide *ngFor="let slide of slides"> <img src="{{slide.imgUrl}}" alt="" style="display: block; width: 100%;"> </slide> 1. Is there a way to substitute the indicators with images ...

Conceal a div element after redirecting to a different HTML page

I have a dilemma with my two HTML pages - index.html and register.html. I am trying to navigate from index.html to register.html, but I want to skip the select region step and go straight to the login page. Here's the code snippet I've been attem ...

What is the best method for uploading photos via ajax in a django application?

Currently, I am in the process of creating a function that allows users to update their profiles by changing their email addresses, names, and profile pictures. While I have been successful in updating emails and names, I have encountered difficulties in u ...

Error with adaptable menu

I am attempting to develop a responsive menu similar to the Bootstrap nav bar using only CSS. I have managed to get the functionality working, but the positioning of the menu grabber is incorrect and I'm unsure how to correct it. The grabber should al ...

Python and Selenium are a powerful combination, but sometimes you may encounter the error message "Element cannot be clicked at point (x,y)

I'm trying to automate the selection of a checkbox on a webpage using Selenium and Python with this line of code: self.driver.find_element_by_id('lg_1166').click() Unfortunately, I'm encountering an error message: Message: Element < ...

What techniques can be used to avoid blinking while forcefully scrolling to the left?

In my previous inquiry about dynamically adding and removing divs on scroll, I was unable to find a satisfactory solution among the responses provided. However, I decided to take matters into my own hands and attempted to implement it myself. My approach ...

Create an HTML table to view JSON data from a cell on a map

Looking to transform the JSON data into a table by organizing the information based on supplier and product. Below is the JSON input and code snippet: $(document).ready(function () { var json = [{ "Supplier": "Supplier1", "Product": "O ...

Designing a dynamic button with changing colors using html and css

Is there a way to design a button with a starting color of red, but changes to orange when the mouse hovers over it? I am looking to add this type of button to my website. ...

Troubleshooting: How to Fix Missing Sum Display in HTML Input Fields

I am new to the world of website programming and I am currently working on creating a basic sum equation using two input fields from the client-side. <!DOCTYPE html> <html> <head> </head> ...

The CSS cubic-bezier fails to smoothly transition back to its initial position

I created an animation that works perfectly when hovering over the target elements, however, it doesn't smoothly transition back to its original position when the cursor moves outside of the target element. Instead, it snaps back abruptly and unattrac ...

Help needed with debugging CSS for IE6 >_<

I have been working on the following website: www.darksnippets.com While the design looks good on Firefox and Chrome, it appears terrible on IE6. For example, on the home page and other pages like , the width is too wide in IE6. I've been unable to ...