Clase pseudo CSS :only-child
La pseudo-clase :only-child coincide con un elemento si es el único hijo de su padre.
El elemento se selecciona solo si su padre no tiene otros hijos de ningún tipo. La pseudo-clase :only-child es equivalente a :first-child:last-child y tiene la misma especificidad (0,2,0).
Versión
Sintaxis
Sintaxis de CSS :only-child
css
:only-child {
css declarations;
}Ejemplo del selector :only-child:
Ejemplo de :only-child
html
<!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>Ejemplo del selector :only-child para la etiqueta <li>:
Ejemplo de :only-child con etiqueta li
html
<!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>Ejemplo del selector :only-child para la etiqueta <em>:
Ejemplo de :only-child con etiqueta em
html
<!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>Ejemplo del selector :only-child para la etiqueta <div>:
Ejemplo de :only-child para la etiqueta div
html
<!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>Práctica
El pseudo-selector :only-child coincide con un elemento