FedKad
FedKad

Reputation: 605

Change style of content depending on another css property value

Say, I want to change the background color of all the content in a paragraph that does not have any text-decoration (like bold, underline, etc.). Is it possible to do it just using CSS with a some kind of syntax like this?

p[text-decoration=none] {
  background-color: yellow;
}

A sample HTML content that this CSS should be applied will be something like this:

<p class="special">Yellow background <b>default background for paragraph</b> yellow
again <i>default</i> once again yellow.</p>

Requirements for the above to work:

  1. Do not add style and/or class attributes to the paragraph contents, i.e., to <b>, <i>, etc.
  2. Do not change the styles for <b>, <i>, etc.
  3. Background-color should be specified for any content (HTML or CSS-style based) that does not have any text-decoration.
  4. The parent of <p> may have a custom background-color, so elements like <b> or <i> should assume that color.

Upvotes: 1

Views: 2027

Answers (1)

s.kuznetsov
s.kuznetsov

Reputation: 15213

It is impossible to make the absolutely correct decision according to your requirements with the help of CSS. But you can apply a little trick, which is to use the CSS variables declared inside :root.

The principle is to use the same background color for the background of the main parent and the background of tags b and i. You need to declare a variable like this:

:root {
    --backColor: yellowgreen;
}

Next, using function var(), assign the declared variable for rules background-color, body tags (parent), b and i:

background-color: var(--backColor);

In pseudo-class :is(), you need to specify tags (b and i) for which the background color of the variable will be assigned.

:root {
    --backColor: yellowgreen;
}

body {
    background-color: var(--backColor);
}

p {
    background-color: yellow;
    display: inline-block;
}

p * {
    display: inherit;
}

p *:is(b, i) {
    background-color: var(--backColor);
}
<p class="special">Yellow background <b>default background for paragraph</b> yellow again <i>default</i> once again yellow.</p>

Upvotes: 2

Related Questions