Example of Only-child and Only-of-type in CSS3 selector

Source: Internet
Author: User

Only-child Selector

The selector :only-child selects only one child element in the parent element, and only one child element. That is, there is only one child element in the parent element of the matching element, and it is a unique child element .

Sample Demo

Using the ": Only-child" selector to control the background style of only one child element, for a better understanding, this example is shown in a contrasting way.

HTML code:


<p class= "POST" >  <p> I am a paragraph </p>  <p> I am a paragraph </p></p><p class= "POST" >  <p> I'm a paragraph </p></p>

CSS code:


. Post p {  background:green;  Color: #fff;  padding:10px;}. Post P:only-child {  background:orange;}

Demo Result:

Only-of-type Selector

“:only-of-type”The selector is used to select an element that is the only child of its parent element of the same type. This may not be a good idea, in other words. “:only-of-type”is to represent an element he has many child elements, and only one of them is unique, and the ": Only-of-type" selector allows you to select only one type child element in the element.

Sample Demo

The ": Only-of-type" selector modifies the background color of only one P element in the container to be orange.

HTML code:


<p class= "wrapper" >  <p> I am a paragraph </p>  <p> I am a paragraph </p>  <p> I am a paragraph </p >  <p> I am a P element </p></p><p class= "wrapper" >  <p> I am a p</p>  <ul >    <li> I'm a list item </li>  </ul>  <p> I'm a paragraph </p></p>

CSS code:


. wrapper > P:only-of-type {  background:orange;}

Demo Result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.