Reputation: 71
I need to add styles to an HTML code element that has duplicate parent elements of the same type.
Example:
<code><code><code>foo</code></code></code>
I only want to apply styles to one of the elements, for example code { padding: 1px; }
actually results in 3px in this example.
I have no control of this HTML as it is generated, it also can have only one parent code element sometimes.
Is it possible to write a CSS rule that ignores the parent elements and only targets the one?
Upvotes: 2
Views: 499
Reputation: 62901
You can use the child combinator >
if you know the depth of the nested element.
The >
selector 'matches only those elements matched by the second selector that are the children of elements matched by the first'.
code > code > code {
border: 1px solid #000000;
padding: 5px;
}
<code><code><code>foo</code></code></code>
The only option that currently works is to target the top-level code
element for styling, then remove the styling from any nested code
elements.
code {
border: 1px solid #000000;
padding: 5px;
}
code code {
padding: 0;
border: 0;
}
<code>foo</code>
<code><code>foo</code></code>
<code><code><code>foo</code></code></code>
<code><code><code><code>foo</code></code></code></code>
Once CSS Selectors Level 4 is implemented you'll be able to use the :has
pseudo-class, like:
code:not(:has(> code))
Example (which won't work in any browser at this point):
code:not(:has(> code)) {
border: 1px solid #000000;
padding: 5px;
}
<code><code>foo</code></code>
<code><code><code>foo</code></code></code>
Upvotes: 2
Reputation: 6827
As per you Question(I have no control of this HTML as it is generated, it also can have only one parent code element sometimes.)
we can use use the selector >
to remove the style for the <code>
tag and apply padding to only the first <code>
only. Check the demo, I hope it was helpful, and by the way, there is no way to write a CSS rule that ignores the parent elements and only targets the one so have to use workarounds like this.
code {
padding: 1px
}
code>code {
padding: 0px
}
code>code>code {
padding: 0px
}
<code>
<code>
<code>foo</code>
</code>
</code>
<code>
<code>foo</code>
</code>
<code>foo</code>
Upvotes: 1
Reputation: 26
You can use the selector ">" as here: https://www.w3schools.com/cssref/sel_element_gt.asp
In your example would be something like this:
code > code > code{
padding:1px;
}
Upvotes: 0
Reputation: 53766
If you know the depth of your code
tags:
code > code > code {
padding: 1px;
}
Upvotes: 0