Here's my problem.
HTML
<div id="content">
<h1>Headline</h1>
<p>First paragraph that needs to be yellow.</p>
<p>Second paragraph that need not change. :) </p>
<p>Third paragraph that need not change. :) </p>
</div>
If I use #content p:first-child {color:yellow; }
it doesn't work because p
isn't the first-child of content
... h1
is the first born.
How can I do this without touching the HTML code?
Thank you!
All the best, Cris
The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
If you want to select an element immediately after another element you use the + selector.
Using the :first-child selector, you can target or select the very first element inside an element, like a DIV. You can use any other element as a container like <section> or <article> etc.
CSS ::first-line Selector The ::first-line selector is used to add a style to the first line of the specified selector. Note: The following properties can be used with ::first-line: font properties. color properties.
a css3 solution
#content > p:first-of-type { color: yellow; }
This is the best way:
$('#content p:first').css('color', 'yellow');
you can use also (CSS, jQuery) nth-of-type
:
#content p:nth-of-type(1) {color:yellow; }
$('#content p:nth-of-type(1)').css('color', 'yellow');
Use the .first()
function (or :first
selector) instead:
$('#content > p').first().css('color', 'yellow');
<script>
$(function(){
$('#content p:first').css('color','yellow');
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With