Home > Back-end >  applying styling to only one element of a class
applying styling to only one element of a class

Time:12-14

I have 3 h1 tags. For example:

<div >
<h1>heading 1</h1>
<h1>heading 2</h1>
<h1>heading 3</h1>
</div>

I want to add padding-bottom to only the last headline tag in this block. the headlines are filled from an array, so it can have any number of headlines

I tried .headline:last-child { padding-bottom: 10px; but it didnt work

CodePudding user response:

If you are populating the h1 from an array and want to change on the last item you have to use the :last-child property as you mentioned. You just targeting it wrong. You need to specify the element of last-child as well, see below:

.headline h1:last-child {
  color: red;
  padding-bottom: 10px; /*in your case use padding bottom*/
}
<div >
  <h1>heading 1</h1>
  <h1>heading 2</h1>
  <h1>heading 3</h1>
</div>

CodePudding user response:

You can use last-of-type to do this. You can read more about last-of-type here.

Below is an example of selecting the last element in a list of elements, no matter how long that list is.

Edit: last-of-type ensures you're only targetting the h1. If you use last-child, a p tag in the array will be styled, not just headings. If that is what you want, you can read more about that here. IF you do want to use last-child specifically, simply replace the last-of-type selector in my example below with it and it will work.

CodePen Link

.headline h1 {
  color: red;
}

.headline h1:last-of-type {
  color: blue;
}
<div >
  <h1>Heading 1</h1>
  <h1>Heading 2</h1>
  <h1>Heading 3</h1>
  <h1>Heading 4</h1>
  <h1>Heading 5</h1>
</div>

  • Related