使用 CSS :focus-within 增强表单交互性

CSSCSSBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索 CSS 中的 :focus-within 伪类,它允许我们在父元素的任何子元素获得焦点时,为该父元素应用样式。我们将利用此功能创建一个视觉上吸引人的表单,当用户与之交互时,表单会改变其外观。通过本实验,你将更好地理解如何使用 CSS 创建交互式表单来提升用户体验。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("`CSS`")) -.-> css/BasicConceptsGroup(["`Basic Concepts`"]) css(("`CSS`")) -.-> css/BasicStylingGroup(["`Basic Styling`"]) css(("`CSS`")) -.-> css/CoreLayoutGroup(["`Core Layout`"]) css(("`CSS`")) -.-> css/IntermediateStylingGroup(["`Intermediate Styling`"]) css/BasicConceptsGroup -.-> css/selectors("`Selectors`") css/BasicStylingGroup -.-> css/colors("`Colors`") css/CoreLayoutGroup -.-> css/margin_and_padding("`Margin and Padding`") css/CoreLayoutGroup -.-> css/borders("`Borders`") css/CoreLayoutGroup -.-> css/width_and_height("`Width and Height`") css/CoreLayoutGroup -.-> css/display_property("`Display Property`") css/IntermediateStylingGroup -.-> css/backgrounds("`Backgrounds`") css/IntermediateStylingGroup -.-> css/pseudo_classes("`Pseudo-classes`") subgraph Lab Skills css/selectors -.-> lab-35201{{"`使用 CSS :focus-within 增强表单交互性`"}} css/colors -.-> lab-35201{{"`使用 CSS :focus-within 增强表单交互性`"}} css/margin_and_padding -.-> lab-35201{{"`使用 CSS :focus-within 增强表单交互性`"}} css/borders -.-> lab-35201{{"`使用 CSS :focus-within 增强表单交互性`"}} css/width_and_height -.-> lab-35201{{"`使用 CSS :focus-within 增强表单交互性`"}} css/display_property -.-> lab-35201{{"`使用 CSS :focus-within 增强表单交互性`"}} css/backgrounds -.-> lab-35201{{"`使用 CSS :focus-within 增强表单交互性`"}} css/pseudo_classes -.-> lab-35201{{"`使用 CSS :focus-within 增强表单交互性`"}} end

子元素获得焦点

虚拟机中已经提供了 index.htmlstyle.css

要在表单的任何子元素获得焦点时更改表单的外观,请使用伪类 :focus-within 为父元素应用样式。例如,在给定的 HTML 代码中,如果任何输入字段获得焦点,form 元素将具有绿色背景。要为子元素应用样式,请使用适当的 CSS 选择器,如 labelinput

<form>
  <label for="username">用户名:</label>
  <input id="username" type="text" />
  <br />
  <label for="password">密码:</label>
  <input id="password" type="text" />
</form>
form {
  border: 2px solid #52b882;
  padding: 8px;
  border-radius: 2px;
}

form:focus-within {
  background: #7cf0bd;
}

label {
  display: inline-block;
  width: 72px;
}

input {
  margin: 4px 12px;
}

请点击右下角的“上线”以在端口 8080 上运行 Web 服务。然后,你可以刷新“Web 8080”标签页来预览网页。

总结

恭喜你!你已经完成了“子元素获得焦点”实验。你可以在 LabEx 中练习更多实验来提升你的技能。

您可能感兴趣的其他 CSS 教程