Псевдокласс CSS :only-child
Псевдокласс :only-child соответствует элементу, если он является единственным дочерним элементом своего родителя.
Элемент выбирается только в том случае, если у его родителя нет других дочерних элементов любого типа. Псевдокласс :only-child эквивалентен :first-child:last-child и имеет ту же специфичность (0,2,0).
Версия
Синтаксис
Синтаксис CSS :only-child
css
:only-child {
css declarations;
}Пример селектора :only-child:
Пример :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>Пример селектора :only-child для тега <li>:
Пример :only-child с тегом 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>Пример селектора :only-child для тега <em>:
Пример :only-child с тегом 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>Пример селектора :only-child для тега <div>:
Пример :only-child для тега 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>Практика
Псевдоселектор :only-child соответствует элементу