好的,以下是补充的伪类示例,以便更好理解各个伪类的实际应用:
互动状态示例
:hover
<button class="hover-button">Hover Me</button>
.hover-button:hover {
background-color: yellow;
}
当用户将鼠标悬停在按钮上时,按钮的背景颜色会变成黄色。
:active
<button class="active-button">Click Me</button>
.active-button:active {
background-color: red;
}
当用户点击按钮时,按钮的背景颜色会变成红色。
:focus、:focus-within 和 :focus-visible
<input class="focus-input" type="text" placeholder="Focus on me">
.focus-input:focus {
border: 2px solid blue;
}
.focus-input:focus-visible {
outline: 2px solid green;
}
当输入框获得焦点时,边框会变成蓝色,通过键盘获得焦点时,显示绿色的外轮廓。
:target
<a href="#section1">Go to Section 1</a>
<div id="section1">This is Section 1</div>
#section1:target {
background-color: lightblue;
}
当 URL 包含 #section1 时,该部分的背景颜色会变成浅蓝色。
表单状态示例
:disabled和:enabled
<button class="btn" disabled>Disabled Button</button>
<button class="btn">Enabled Button</button>
.btn:disabled {
background-color: grey;
}
.btn:enabled {
background-color: green;
}
禁用的按钮背景为灰色,启用的按钮背景为绿色。
:checked和:indeterminate
<input type="checkbox" class="check" id="check1" checked>
<label for="check1">Checked</label>
<input type="checkbox" class="check" id="check2">
<label for="check2">Unchecked</label>
<input type="checkbox" class="check" id="check3">
<label for="check3">Indeterminate</label>
.check:checked + label {
color: green;
}
.check:indeterminate + label {
color: orange;
}
选中的复选框标签颜色为绿色,不确定状态的复选框标签颜色为橙色。
:placeholder-shown
<input class="placeholder-input" type="text" placeholder="Enter text here">
.placeholder-input:placeholder-shown {
border: 1px dashed red;
}
当输入框显示占位符时,边框为红色虚线。
验证状态
<input class="email-input" type="email" placeholder="Enter your email" required>
.email-input:valid {
border: 2px solid green;
}
.email-input:invalid {
border: 2px solid red;
}
有效的电子邮件输入框边框为绿色,无效的为红色。
按索引、顺序和出现次数选择元素示例
:first-child和:last-child
<ul class="list">
<li>First Item</li>
<li>Second Item</li>
<li>Last Item</li>
</ul>
.list li:first-child {
color: blue;
}
.list li:last-child {
color: red;
}
第一个列表项文字为蓝色,最后一个列表项文字为红色。
:nth-child和:nth-of-type
<ul class="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
.list li:nth-child(odd) {
background-color: lightgray;
}
.list li:nth-of-type(3n) {
color: orange;
}
奇数项背景为浅灰色,每三个项的文字为橙色。
查找空元素示例
:empty
<div class="container">
<p>Not Empty</p>
<p></p>
</div>
.container p:empty {
display: none;
}
空的段落元素将被隐藏。
查找和排除多个元素示例
:is()
<div class="post">
<h2>Heading</h2>
<p>Paragraph</p>
<img src="image.jpg" alt="Image">
</div>
.post :is(h2, p, img) {
border: 1px solid black;
}
所有的 h2、p 和 img 元素将有黑色边框。
:not()
<a href="#" class="link">Link with class</a>
<a href="#">Link without class</a>
a:not([class]) {
color: blue;
}
没有 class 属性的链接文字将为蓝色。
这些示例展示了常见伪类的实际应用,希望能帮助您更好地理解和使用伪类。
本文是原创文章,采用 CC BY-NC-SA 4.0 协议,完整转载请注明来自 小朱
评论
隐私政策
0/500
滚动到此处加载评论...


