Search code examples
csspseudo-elementcss-content

Children :before content inheritance


The title might be a little bit confusing but I wonder why is it impossible for a child element to inherit it's parent ::before content. for example:

HTML:

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

CSS:

.foo::before {
    content: 'bar';
}

.foo .baz::before {
    content: inherit;
}

I have tried it that way, and even this way:

.foo > .baz::before {
    content: inherit;
}

and this one:

.foo::before ~ .baz::before {
    content: inherit;
}

...and none of the above worked... Is it possible at all? if not, which options do I have in order to achieve this?

UPDATE

I think I might found a way to do such thing:

.foo {
    content: 'bar';
}

.foo > .baz,
.foo > .baz::before {
    content: inherit;
}

Solution

  • A ::before/::after pseudo-element cannot inherit from another ::before/::after pseudo-element. A pseudo-element can only inherit from its originating element — this is the element that the pseudo-element is attached to. A pseudo-element cannot even inherit from the parent of its originating element, unless the originating element itself is also inheriting from its parent and the property involved is not content.

    In your example, .foo::before can only inherit from the .foo it's attached to, and likewise for .baz::before and .baz. .baz::before cannot inherit from .foo::before, so what you're trying to do is not possible. There does not appear to be a reliable way to ensure that one pseudo-element always inherits from another pseudo-element through CSS alone without enforcing this within the markup itself.