0

Let's say I have an html page containing 3 blockquotes. How to set background of the very first blockquote (of the page) to red with css without using classes?

I already tried...

body blockquote: first-child {
    background-color: red;    
}

...without success.

Thanks.

Harry
  • 87,580
  • 25
  • 202
  • 214
Bronzato
  • 9,438
  • 29
  • 120
  • 212
  • Possible duplicate of http://stackoverflow.com/questions/9439321/matching-first-element-in-whole-document (not vtc'ed, just linking). – Harry Feb 22 '15 at 13:41

2 Answers2

0

There is no way to do that with CSS alone in the general case. There is no “first descendant of a type” selector, only “first child of a type”.

Usually, however, assumptions can be made about the markup. For definiteness, assume that the page content is inside <div id=content>...</div> and that all blockquote elements appear as children of that element. Then you can just use the :first-of-type selector:

<style>
#content blockquote:first-of-type {
    background-color: red;    
}
</style>
<div id=content>
<p>Some stuff
<blockquote>I am quoted.</blockquote>
<p>Some more stuff
<blockquote>I am quoted, too.</blockquote>
</div>
  
Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
  • I tried as you suggest... here is the test page: http://testjeanschwartz.weebly.com/ the problem is that the parent content I tried to use is `.container` but this is not a direct parent of the blockquote and it does not seems to work. Thanks anyway. – Bronzato Feb 22 '15 at 12:26
  • @Bronzato, in that case, the general part of the answer applies: you cannot. – Jukka K. Korpela Feb 22 '15 at 18:38
0

Why your CSS doesn't work :

Your HTML structure :

body
__ parent
____ blockquote
__ parent
____ blockquote

CSS :

body blockquote: first-child {
    background-color: red;    
}

What this CSS selector actually does is - it selects every blockquote which occurs first in its parent and not body.

First-child doesn't work respective to the body tag when the elements are nested in other elements. It works respective to the parent.

Try using this instead :

td.wsite-multicol-col:first-child blockquote {
    background: red;
}

This selects the first col and sets styles for its child (blockquote). It doesn't set style to first blockquote of the page.

The Pragmatick
  • 5,379
  • 27
  • 44
  • It is working for the first blockquote of the first `col` as you said. But how to set style for the first blockquote of the page ? Assuming there may be several `col` on the page ? Thanks anyway. – Bronzato Feb 22 '15 at 13:02
  • I updated the demo page http://testjeanschwartz.weebly.com to show the problem of having 2 blockquotes getting the style when I only need the 1st one. – Bronzato Feb 22 '15 at 13:04
  • You can't do it in CSS with such deeply nested markup. You can try JS. – The Pragmatick Feb 22 '15 at 13:16