I’m trying to find an elegant solution to styling a child element, when it has the same class as the parent element.
I suspect Javascript will be required to make this work, although I’ve also explored ways to do it with SASS variables, without success.
My HTML structure looks like this:
<div class="film parent">
<div class="film child">
</div>
</div>
Currently I am writing out all of the possible options in a long css command like:
.film .film,
.music .music,
.art .art {
color: red;
}
etc.
This isn’t ideal, as new class names will appear in here over time, and I’d like a catch-all style to account for those.
2
Answers
Here you can use CSS Selectors to style the parent and child tag easily
You can use
:first-child
selector to select the first child of the taghere it will select the first child of the tag with a class film and will change the colour to red
You can read more about CSS Selector
Here
I think I would actually go down the
jss
route at this point. Though,there is asimple
js way too.Absolutely! JSS (JavaScript styles) is another solution to this problem. It gives you the power of JavaScript to generate and manage styles, so you can dynamically create styles based on conditions and data.
Here’s a basic example of how you might tackle this issue with JSS:
First, you would set up JSS. Typically, you’d do this by adding the required libraries:
Create and apply the styles ( I would research more still):
// Apply the style
const dynamicClass = styleChildWithParentClass(‘film’);
In your HTML, you’d then add the
dynamicClass
to your elements:I think, on a large scale project I would look into JSS more deeply and setup the project in a "real" way.
But ye, without JSS, this makes me sick, however there is
nothing
wrong with it expect the fact you’re selecting every single element on the page…. :thumbs_up: So really you should change thisdocument.querySelectorAll('*')
to be more targeting e.g document.querySelectorAll(‘.where_dynamic_styles_happen’)