CSS :only-child Pseudo Class
The :only-child pseudo-selector matches an element if it is the only child of its parent.
The element is selected only if its parent has no other children of any type. The :only-child pseudo-class is the same as :first-child, :last-child or :nth-child(), :nth-last-child(), but with a lower specificity.
Version ¶
Selectors Level 4
Selectors Level 3
Syntax¶
:only-child {
css declarations;
}
Example of the:only-child selector:¶
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:only-child {
background: #1c87c9;
}
</style>
</head>
<body>
<h2>:only-child selector example</h2>
<div>
<p>Lorem ipsum is simply dumnmy text.</p>
</div>
<div>
<p>Lorem ipsum is simply dummy text.</p>
<p>Lorem ipsum is simply dummy text.</p>
</div>
</body>
</html>
Example of the :only-child selector for the <li> tag:¶
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
ul li {
list-style-type: square;
}
li:only-child {
color: blue;
list-style-type: disc;
}
</style>
</head>
<body>
<h2>:only-child selector example</h2>
<ol>
<li>
One element
<ul>
<li>This list has just one element.</li>
</ul>
</li>
<li>
Two elements
<ul>
<li>This list has two elements.</li>
<li>This list has two elements.</li>
</ul>
</li>
<li>
Three elements
<ul>
<li>This list has three elements.</li>
<li>This list has three elements.</li>
<li>This list has three elements.</li>
</ul>
</li>
</ol>
</body>
</html>
Example of the :only-child selector for the <em> tag:¶
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
em:only-child {
background-color: #8ebf42;
}
</style>
</head>
<body>
<h2>:only-child selector example</h2>
<p>This is a <em>paragraph</em>.</p>
<p>This is a paragraph.</p>
</body>
</html>
Example of the :only-child selector for the <div> tag:¶
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div:only-child {
color: #8ebf42;
font-weight: bold;
}
div {
display: block;
margin: 6px;
padding: 5px;
outline: 1px solid #1c87c9;
}
div div {
display: inline-block;
}
</style>
</head>
<body>
<h2>:only-child selector example</h2>
<div>
<div>I am an only child.</div>
</div>
<div>
<div>I am the 1st sibling.</div>
<div>I am the 2nd sibling.</div>
<div>
I am the 3rd sibling,
<div>but this is an only child.</div>
</div>
</div>
</body>
</html>
0 Comments
CAN FEEDBACK
Emoji