{"id":14242,"date":"2011-09-06T20:24:53","date_gmt":"2011-09-07T03:24:53","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=14242"},"modified":"2019-08-08T14:02:46","modified_gmt":"2019-08-08T21:02:46","slug":"only-child","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/selectors\/o\/only-child\/","title":{"rendered":":only-child"},"content":{"rendered":"

The :only-child<\/code> pseudo-class<\/a> selector property in CSS<\/abbr> represents an element that has a parent element and whose parent element has no other element children. This would be the same as :first-child:last-child<\/code> or :nth-child(1):nth-last-child(1)<\/code>, but with a lower specificity.<\/p>\n

div p:only-child {\r\n  color: red;\r\n}<\/code><\/pre>\n

For example, if we nest paragraphs within a <div><\/code> like so…<\/p>\n

<div>\r\n  <p>This paragraph is the only child of its parent<\/p>\r\n<\/div>\r\n \r\n<div>\r\n  <p>This paragraph is the first child of its parent<\/p>\r\n  <p>This paragraph is the second child of its parent<\/p>\r\n<\/div><\/code><\/pre>\n

Now we can style the only <p><\/code> of our first child <div><\/code>. The subsequent <div><\/code> and it’s children will never be styled as the parent container holds more than one child (i.e. the p tags).<\/p>\n

p:only-child {\r\n  color:red;\r\n}<\/code><\/pre>\n

We could also mixin additional pseudo-classes like this example that selects the first paragraph within our nested div and the only-child of div.contain<\/code>.<\/p>\n

<div class=\"contain\">\r\n  <div>\r\n    <p>Hello World<\/p>\r\n    <p>some more children<\/p>\r\n  <\/div>\r\n<\/div><\/code><\/pre>\n
div.contain div:only-child :first-child {\r\n  color: red;\r\n}<\/code><\/pre>\n

:only-child<\/code> won’t work as a selector if your parent element contains more than one child with an identical tag. For example\u2026<\/p>\n

<div class=\"contain\">\r\n  <div>\r\n    <h1>Div Child 1<\/h1>\r\n    <p>paragraph1<\/p>\r\n    <p>paragraph2<\/p>\r\n  <\/div>\r\n\r\n  <div>\r\n    <h1>Div Child 2<\/h1>\r\n    <p>paragraph1<\/p>\r\n    <p>paragraph2<\/p>\r\n  <\/div>\r\n\r\n  <div>\r\n    <h1>Div Child 3<\/h1>\r\n    <p>paragraph1<\/p>\r\n    <p>paragraph2<\/p>\r\n  <\/div>\r\n<\/div><\/code><\/pre>\n
div.contain div:only-child {\r\n  color: red;\r\n}<\/code><\/pre>\n

This will result in no divs inheriting the color red as the parent contains more than 1 child (the 3 unnamed divs).<\/p>\n

Related Properties<\/h3>\n