📜  css first child - CSS (1)

📅  最后修改于: 2023-12-03 14:40:16.832000             🧑  作者: Mango

CSS First Child

In CSS, the :first-child pseudo-class is used to select the first child element within a parent element. This selector is often used for styling the first element of a list or the first paragraph of a section.

Syntax

The :first-child selector is written with a colon followed by the keyword "first-child". It's added to the end of a selector to select the first child element within that selector.

The syntax is as follows:

selector:first-child { 
   /* property declarations */ 
}
Example

Suppose you have an HTML unordered list containing several list items. You can use the :first-child selector to style the first list item in a different color:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
ul li:first-child {
  color: red;
}

The above CSS rule will apply the color: red; property only to the first list item, because it is the first child of its parent ul element.

Compatibility

The :first-child selector is supported by all major web browsers, including Internet Explorer 9 and later.

Conclusion

The :first-child selector is a powerful tool in CSS for targeting the first child of a parent element. This selector can be used to create unique styles for the first item in a list or to add special formatting to the first paragraph of a section. By combining the :first-child selector with other CSS selectors, you can create complex styles that target specific elements on your web page.