Trong CSS, bộ chọn :only-child
được dùng để chọn phần tử duy nhất. Nó đại diện cho một phần tử không có bất kỳ anh chị em ruột nào.
Syntax:
:only-child {
// CSS property
}
Example 1:
html<!DOCTYPE html>
<html>
<head>
<title>:only-child selector</title>
<style>
h1 {
color: green;
text-align: center;
}
h2 {
text-align: center;
}
div:only-child {
color: white;
background: green;
}
div {
display: block;
margin: 6px;
font-size: 17px;
padding: 5px 8px;
border: solid 2px grey;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>:only-child selector</h2>
<div>
<div>I am an only child.</div>
</div>
<div>
<div>I am the 1st child.</div>
<div>I am the 2nd child.</div>
<div>I am the 3rd child, </div>
<div>child of parent.</div>
</div>
</body>
</html>
Output: Example 2:
<!DOCTYPE html>
<html>
<head>
<title>:only-child selector</title>
<style>
h1 {
color: green;
text-align: center;
}
h2 {
text-align: center;
}
li:only-child {
color: green;
}
li {
font-size: 20px;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>:only-child selector</h2>
<ol>
<li>Data Structures</li>
<ul>
<li>Arrays </li>
</ul>
<li>Languages</li>
<ul>
<li>C++ </li>
<li>Python</li>
</ul>
<li>Algorithms</li>
<ul>
<li>Searching Algorithms</li>
<li>Sorting Algorithms</li>
<ul>
<li>Bubble sort </li>
</ul>
</ul>
</ol>
</body>
</html>
Output: Supported Browser: Các trình duyệt hỗ trợ bộ chọn
:only-child
được liệt kê dưới đây:
- Google Chrome 2.0 trở lên
- Edge 12.0 trở lên
- Firefox 1.5 trở lên
- Safari 3.1 trở lên
- Opera 9.5 trở lên