0

HTML:

<form id="myForm">
  <p>Lorem ipsum</p>
  <p>Lorem ipsum 2 </p>
  <div class="section">Section 1</div>
  <div class="section1">section 2</div>
  <div class="section">Section 3</div>
  <div class="section1">section 4</div>
  <p>Lorem ipsum</p>
</form>`

CSS:

#myForm div.section1:first {
  color: red;
  font-size: 1.5em;
}

Question: How to write CSS selector to select the first section1 CSS class under the form with text 'section 2'

The above CSS is not working

skyline3000
  • 7,639
  • 2
  • 24
  • 33
Manju
  • 2,520
  • 2
  • 14
  • 23

3 Answers3

1

You can't target it like that, but you can do something like this bellow. Basically overwriting the rest with the default.

A much better approach would be to have different markup.

#myForm div.section1 {
  font-size:1.5em;color:red;
}

#myForm div.section1 ~ .section1 {
  font-size:1em;
  color:black;
}
<form id="myForm">
  <p>Lorem ipsum</p><p>Lorem ipsum 2 </p>
  <div class="section">Section 1</div>
  <div class="section1">section 2</div>
  <div class="section">Section 3</div>
  <div class="section1">section 4</div>    <p>Lorem ipsum</p>
</form>
Ferenc Kamras
  • 184
  • 1
  • 6
  • Can you explain why you can't target it this way though? I thought `#myForm div.section1:first-of-type` should work? – Callan Heard Jun 30 '16 at 13:51
  • @CallanHeard: My answer below explains it - section1 isn't an element, but a class, and :first-of-type only sorts through elements. – TheThirdMan Jun 30 '16 at 13:51
  • You might find this helpful http://stackoverflow.com/questions/6447045/css3-selector-first-of-type-with-class-name – Ferenc Kamras Jun 30 '16 at 14:04
0

There is no :first selector.

As discussed in great detail here, there is no :first-of-class selector either, just a :first-of-type one. The linked answer also supposes a workaround, which for your answer looks like this:

#myForm {
  color: black;
  font-size: 15px;
}
#myForm > div.section1 {
  font-size: 19px;
  color: red;
}
#myForm > div.section1 ~ div.section1 {
  font-size: 15px;
  color: black;
}
<form id="myForm">
  <p>Lorem ipsum</p>
  <p>Lorem ipsum 2</p>
  <div class="section">Section 1</div>
  <div class="section1">Section 2</div>
  <div class="section">Section 3</div>
  <div class="section1">Section 4</div>
  <p>Lorem ipsum</p>
</form>

This works by setting all .section1 divs to a certain style, then re-setting them to their original style with another definition using the ~ selector.

Community
  • 1
  • 1
TheThirdMan
  • 1,482
  • 1
  • 14
  • 27
0

I think this would make #myForm div.section1:nth-of-type(2) { font-size: 1.5em; color: red; }

vignesh
  • 951
  • 5
  • 13
  • That would only work for the markup at hand, but it doesn't solve the problem of styling the first element of class section1. Also, since this is your second answer, note that you can delete answers you don't think are fitting anymore to remove them from the question. – TheThirdMan Jun 30 '16 at 14:43