<!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>
There is an easier way than Sapph’s method that is CSS2 using the adjacent selector:
.car div + h2{}