14

I have this :

<div class="foo">
    <h3>Title</h3>
    Some text I want to select using a CSS selector.
    <div class="subfoo">Some other text</div>
</div>

Is it possible to select only "Some text I want to retrieve using a CSS selector" using a single expression of CSS selectors ?

Reveclair
  • 2,399
  • 7
  • 37
  • 59
  • There is no CSS selector that excludes inheritance to inner elements. You will have to overwrite unwanted inherited properties on the child elements. – connexo Jul 30 '15 at 09:17
  • Have you tried `.foo:not(.foo *)`? I'm unsure it this is possible. – connexo Jul 30 '15 at 09:24
  • @connexo Thanks for your answer, but that does not work : http://jsfiddle.net/qw70ok4b/, you are right I think that's impossible using just one single expression – Reveclair Jul 30 '15 at 09:30
  • @Reveclair check the answer I posted, I think this will be useful to you – Sachink Jul 30 '15 at 09:32
  • I wasn't actually expecting it to work, but it's good you tried. – connexo Jul 30 '15 at 09:32
  • 2
    @connexo: That would be selecting any `.foo` that is itself not a descendant of another `.foo`. – BoltClock Jul 30 '15 at 10:00

3 Answers3

8

It's not possible to do in a clean manner with pure CSS.

As Vangel as suggested I recommend setting the styling for it in a .foo selector then apply overrides for other elements:

.foo{
  //Some text styles
}
.foo *{
  //Overriding styles
}

However the best option would be to make changes to the HTML to place the text in its own element so it can be styled in isolation:

<div class="foo">
    <h3>Title</h3>
    <span>Some text</span>
    <div class="subfoo">Some other text</div>
</div>

.foo span
{
   //Some text styling
}
Curtis
  • 101,612
  • 66
  • 270
  • 352
2

You could just add

.foo {
  color: red;
}

and then override if you want different styles at span or .subfoo

Vangel Tzo
  • 8,885
  • 3
  • 26
  • 32
  • 1
    Keep in mind, editing .foo will cause all of its children to have red text, unless specified otherwise. – Izzy Jul 30 '15 at 09:17
1

I Will suggest you to use reverse methodology.
Set inherit color to text which is not in the tag (red) and the different color for all text which is not in the tag.

 .foo > *{
  color: black;
}
.parentColor{
    color:red;
}
<div class="parentColor">
    <div class="foo">
        <h3>Title</h3>
        Some text I want to select using a CSS selector.
        <div class="subfoo">Some other text</div>
    </div>
</div>

check fiddle

Sachink
  • 1,425
  • 10
  • 22
  • The application of `color` is just an example. He might also be wanting to differentiate regarding an arbitrary number of other css properties which probably not all child elements have in common. – connexo Jul 30 '15 at 09:34
  • @connexo you are right, if the scope is large or he wanted separate color for each inner tag than he will have to overwrite the parent color. – Sachink Jul 30 '15 at 09:39