How do I style the first and last elements of a specific type using CSS?
Davide S
davide s profile pic

To style the first and last elements of a specific type using CSS, you can combine the:first-of-type and:last-of-type pseudo-classes with a type selector. This allows you to target and apply styles specifically to the first and last elements of a particular type within a parent container. Here's a step-by-step guide on how to achieve this: 1. HTML Markup: Start by creating the HTML structure with elements of the specific type:

1
2
3
4
5
6
7
  <div class="container">
     <p>First Paragraph</p>
     <p>Second Paragraph</p>
     <p>Third Paragraph</p>
     <!-- Add more paragraphs or elements of the specific type if needed -->
   </div>
   

In this example, we have a container

that contains several

elements. These

elements represent the specific type of elements that you want to target. 2. CSS Styling: Apply CSS styles to target the first and last elements of the specific type:

1
2
3
4
5
6
7
8
 .container p:first-of-type {
     /* Styles for the first paragraph */
   }

   .container p:last-of-type {
     /* Styles for the last paragraph */
   }
   

The.container p:first-of-type selector targets the first

element within the.container div. You can apply any desired styles to this selector. The.container p:last-of-type selector targets the last

element within the.container div. You can define the styles that should be applied to the last element. Note that the:first-of-type and:last-of-type pseudo-classes select the first and last elements of their respective types, regardless of their class or ID. 3. Example Styling:

1
2
3
4
5
6
7
8
9
10
 .container p:first-of-type {
     font-weight: bold;
     color: blue;
   }

   .container p:last-of-type {
     font-style: italic;
     color: red;
   }
   

In this example, the first

element within the.container div will have a bold font weight and a blue color. The last

element will have an italic font style and a red color. By following these steps and customizing the CSS styles to fit your design requirements, you can style the first and last elements of a specific type using CSS. Remember to adjust the type selector and desired styles accordingly.