0

I wonder if there is any way to set properties to an element but not its children.

E.g

<div>
<span>A child</span>
</div>

That the span child will not get affected.

So if I want to for example give the div a blur filter and don't want to affect the children of the element, how do I do it?

4 Answers4

1

You could set the required property on the element you want to affect, then select the children of this element and unset the same property or give it a different value.

Does this answer your question?

Tess
  • 140
  • 10
1

CSS is hierarchical; any attribute applied to a parent is automatically inherited by the child:

Inheritance

The only way to give a parent an attribute while simultaneously excluding the child is to additionally give the child an attribute that overrides the parent (with higher specificity):

Override

This is best done with the initial value (which 'resets') the value, though you can use any other value you like:

div {
  color: red;
}

div > span {
  color: initial;
}
<div>Parent
  <span>A child</span>
</div>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

you can give separate classes to them and specify options separately in css.

man of knowledge
  • 1,077
  • 7
  • 13
0

Not if you target the div (in this case) directly, then the span is force-blurred as well.

But, you could fake the div with a pseudo element, perhaps something like this:

div {
    width: 200px;
    height: 200px;
    position: relative;
}

/* A fake box with the same dimensions as the div */
div::before {
    content: "";
    background: red;
    display: block;
    filter: blur(10px);
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

span {
    position: relative; /* Z-index purposes */
}
<div>
    <span>I'm not blurry :D</span>
</div>
Cody MacPixelface
  • 1,348
  • 10
  • 21