user3872094 user3872094 - 4 months ago 8
HTML Question

add css to named first children

This question can be the extension to my previous question Apply CSS for first letter.

Now in my current scenario, I want to apply style for the first div with class as

section-sect1
's para.

Below is my HTML.

<div class="chapter">
<div class="figure">
<img class="graphic" src="img.jpg" alt=""></div>
<div class="section-sect1">
<a name="CH_00001-SEC-1"></a>
<div class="section-title">
<span class="section-num"></span> Title</div>
<div class="para">Text1
</div>
<div class="para">Text2
</div>
</div>
<div class="section-sect1">
<a name="CH_00001-SEC-1"></a>
<div class="section-title">
<span class="section-num"></span> Title</div>
<div class="para">Text1
</div>
<div class="para">Text2
</div>
</div>
</div>


My CSS is

.chapter .section-sect1:first-of-type .section-title + .para:first-letter {
border: 1px solid;
font-weight: bold;
color: red;
}


Here When I use the below CSS.

.chapter .section-sect1 .section-title + .para:first-letter {
border: 1px solid;
font-weight: bold;
color: red;
}


it is selecting the first letter of all the
section-sect1
, But I want to select only the first
section-sect1
of
.chapter
.

Here is a working fiddle. https://jsfiddle.net/8b5z8gb4/3/

please let me know how Can I fix this.

Answer

Unfortunately, :first-of-type doesn't work with classes, only with html tags. However in your case, you could do something like this:

.chapter .figure + .section-sect1 .section-title + .para:first-letter {
    border: 1px solid;
    font-weight: bold;
    color: red;
}

But if you can't use .figure, you will have to add a class on your first .section-sect1, or change his tag, so you can use a tag instead of a class in the css:

<div class="chapter">
  <div class="figure">
    <img class="graphic" src="img.jpg" alt=""></div>
  <section class="section-sect1">
    <a name="CH_00001-SEC-1"></a>
    <div class="section-title">
      <span class="section-num"></span> Title</div>
    <div class="para">Text1
    </div>
    <div class="para">Text2
    </div>
  </section>
    <section class="section-sect1">
    <a name="CH_00001-SEC-1"></a>
    <div class="section-title">
      <span class="section-num"></span> Title</div>
    <div class="para">Text1
    </div>
    <div class="para">Text2
    </div>
  </section>

</div>


.chapter section:first-of-type .section-title + .para:first-letter {
    border: 1px solid;
    font-weight: bold;
    color: red;
}
Comments