<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
h2:first-child
{
background:yellow;
}
</style>
</head>
<body>
<div class="car">
<div>Something</div>
<h2>I want to style this</h2>
<p>bla bla</p>
<h2>I don't want to style this</h2>
<p>bla bla bla</p>
</div>
</body>
</html>
I'm having trouble styling the first h2, "I want to style this" since I have a div right before that first h2 I can't select it, but if it weren't there it'll work. Without editing the html (and without using js of course) is there a way to select that first h2? Or is wrapping the h2's with another element like below the only way?
<div class="car">
<div>Something</div>
<div>
<h2>I want to style this</h2>
<p>bla bla</p>
<h2>I don't want to style this</h2>
<p>bla bla bla</p>
</div>
</div>
The :first-child selector is used to select the specified selector, only if it is the first child of its parent.
CSS ::first-letter Selector The ::first-letter selector is used to add a style to the first letter of the specified selector. Note: The following properties can be used with ::first-letter: font properties. color properties.
You can just add this line to your CSS: h2 { background-color: #000000; color: #123123; //You can change these properties to whatever you want. } I haven't said to add inline CSS, There is already inline CSS. See the original question and read my answer again.
You start with -n, plus the positive number of elements you want to select. For example, li:nth-child(-n+2) will select the first 2 li elements.
If you're willing to branch into CSS3, the first-of-type
selector is exactly what you're trying to accomplish.
Here's an example: http://jsfiddle.net/m3yrR/1/
first-of-type
will always select the first occurrence of an element at any level. So for your case, it would style the first <h2>
at any level in the markup tree. You can of course use more specific selectors to limit where it gets selected. :)
Otherwise, yes, you'll have to do something like wrap it in another <div>
, make sure it's the first element, and then do div > h2:first-child
. Or just h2:first-child
, if you want to be less specific.
Just make sure it's the first child (!!) of its parent, and be specific as you need to be with the parent-child hierarchy.
There is an easier way than Sapph's method that is CSS2 using the adjacent selector:
.car div + h2{}
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