search
HomeWeb Front-endHTML Tutorial复选框的 CSS 魔法_html/css_WEB-ITnose

原文: Checkbox Trickery with CSS

翻译:涂鸦码龙

Checkbox 复选框相当好用,加对 CSS 魔法有奇效。此文旨在展示一些利用 checkbox 实现的有创意的东西,并且文中的例子 没用 JavaScript 哟。

基本配方

从 HTML 着手。

<input id="toggle" type="checkbox"><label for="toggle">

此处无技巧可言。

input { position: absolute; left: -9999px;}

为什么不用 display: none?因为屏幕阅读机和键盘 Tab 会忽略它。此方法让 保持在文档流中,但是让它离屏隐藏(超出屏幕可见范围达到隐藏)。

隐藏 以后,我们更容易大展身手。我们仍需传达选中/未选两种状态,但是可以通过

input:checked + label { /* 牛X闪闪的样式 */}

我们使用 :checked伪类, 和相邻兄弟元素选择器( +)的组合达到目的,当复选框选中时,找到紧随其后的

input:checked + label::before { /* 指示器的样式 */}

来,看看实际效果吧。例子用到了以上提及的基本配方,把一个普普通通的复选框改造得当人眼前一亮。

See the Pen Checkbox Trickery: Simple Toggleby Will Boyd ( @lonekorean) on CodePen.

最大的好处是,包含在

中的复选框的值仍然可以被提交。我们只改变了外观,并没有影响功能。

隐藏/显示内容

目前为止,我们都是给

See the Pen Checkbox Trickery: Form Disclosureby Will Boyd ( @lonekorean) on CodePen.

:checked伪类对单选按钮同样奏效,考虑到这一点,“How did you hear about us?”这块的 HTML 用到了单选按钮。

<input id="how-friend" name="how" type="radio"><label for="how-friend" class="side-label">From a friend</label><input id="how-internet" name="how" type="radio"><label for="how-internet" class="side-label">Somewhere on the internet</label><input id="how-other" name="how" type="radio"><label for="how-other" class="side-label">Other...</label><div class="how-other-disclosure">    <label for="how-other-explain" class="top-label">Please explain</label>    <textarea id="how-other-explain"></textarea></div>

单选按钮指示器利用

.side-label::after { display: none; /* 其它样式 */}input:checked + .side-label::after { display: block;}

一直隐藏,直到“Other…”单选按钮选中时才显示。我使用了 display: none隐藏
,因为这次我确实想让屏幕阅读器和键盘 Tab 在内容隐藏时忽略它。当单选按钮选中时,利用 CSS 显示

#how-other:checked ~ .how-other-disclosure { display: block;}

之前我们一直使用相邻兄弟选择器( +),不过这次得用一般兄弟选择器( ~)。它俩很相似,但是可以找到非相邻的兄弟元素,比如我们的

树状文件夹

我们可以活用之前例子中的技巧,实现一个树状文件夹组件,同样具备隐藏 / 显示两种功能。

See the Pen Checkbox Trickery: Folder Treeby Will Boyd ( @lonekorean) on CodePen.

单个文件夹的 HTML 如下:

<div>    <input id="n-1" type="checkbox">    <label for="n-1">Blue</label>    <div class="sub">        <a href="#link">Mana Leak</a>        <a href="#link">Time Warp</a>    </div></div>

Font Awesome 图标用于表示选中(打开)和未选(关闭)状态。

label::before, a::before { display: block; position: absolute; top: 6px; left: -25px; font-family: 'FontAwesome';}label::before { content: '\f07b'; /* closed folder */}input:checked + label::before { content: '\f07c'; /* open folder */}a::before { content: '\f068'; /* dash */}

文件夹里的内容通过一般兄弟选择器( ~)实现显示 / 隐藏。这就是 HTML 外面包裹额外

的原因,为了确保选择器能够选到元素,打开兄弟文件夹。

input:checked ~ .sub { display: block;}

理所当然,文件夹可以嵌套。只需把另一个文件夹的 HTML 放入

即可。点击 “Multicolor”看看效果吧。

最后,我们聊一下重置按钮。

<input type="reset" value="Collapse All">

表单的重置按钮很少有人用,不过这里巧用了一下。点击重置按钮,所有复选框恢复成初始的未选中状态,关闭了所有文件夹。有意思吧。

Split List(分隔列表)

这个例子依据已做或未做,把列表选项分成两部分。

See the Pen Checkbox Trickery: To-Do Listby Will Boyd ( @lonekorean) on CodePen.

HTML 像这样:

<div class="items">    <input id="item1" type="checkbox" checked>    <label for="item1">Create a to-do list</label>        <!-- more items -->        <h2 id="Done">Done</h2>    <h2 id="Not-Done">Not Done</h2></div>

分隔列表是由 CSS flexbox 实现的,这是关键的 CSS。

.items { display: flex; flex-direction: column;}.done { order: 1;}input:checked + label { order: 2;}.undone { order: 3;}label { order: 4;}

CSS flexbox 可以使用 order属性重排元素。当复选框选中的时候,

下面移到了 “Done”

下面。

不幸的是,键盘导航和 许多屏幕阅读器会遵循元素在 DOM 中的顺序,即使它们被 CSS flexbox 做了视觉上的重排。这就导致 “Done”和“Not Done”的标题对于屏幕阅读器无用,这便是我给它们加了 aria-hidden="true"的原因 —— 被忽略总比引起混淆强。此外,通过键盘和屏幕阅读器完全可以控制分隔列表,正确显示列表项的状态(选中 / 未选)。

如果你对“Done”和“Not Done”其后的计数实现感到好奇,它们用到了 CSS counters。想深入学习的话,可以看 这篇文章。

分组筛选

压轴的例子展示了如何根据筛选条件,高亮显示交叉区域的数据。

See the Pen Checkbox Trickery: Group Filterby Will Boyd ( @lonekorean) on CodePen.

这是简短的 HTML 。注意一下 data-teams属性是由空格分隔的列表,它们每一项恰恰与单选按钮的 id属性一致。我就是这么把角色跟队伍匹配起来的。

<input id="original" type="radio" name="team" checked><label for="original">Original X-Men</label><!-- 省略更多团队 --><br><ul class="characters">    <li id="angel" data-teams="original force factor hellfire">        <h2 id="Angel">Angel</h2>        <img src="/static/imghwm/default1.png"  data-src="ct-angel.png"  class="lazy" alt="">    </li>        <!-- 省略更多角色 --></ul>

关于可访问性,我使用了空的 alt属性,因为角色的名字已显示在

标签中了 —— 每个名字读两次也没有必要。此外,我没有真正的隐藏 复选框的 CSS 魔法_html/css_WEB-ITnose元素(只是收缩和渐隐),屏幕阅读器可以轻易的跳过未高亮的角色。我仅仅需要隐藏

当选择团队的时候,高亮对应的角色,CSS 是这么实现的。

#original:checked ~ .characters [data-teams~="original"] h2,#force:checked ~ .characters [data-teams~="force"] h2,#factor:checked ~ .characters [data-teams~="factor"] h2,#hellfire:checked ~ .characters [data-teams~="hellfire"] h2 { /* styles to show character name */}#original:checked ~ .characters [data-teams~="original"] img,#force:checked ~ .characters [data-teams~="force"] img,#factor:checked ~ .characters [data-teams~="factor"] img,#hellfire:checked ~ .characters [data-teams~="hellfire"] img { /* styles to show character avatar */}

我清楚这些选择器看起来有点吓人,不过也不赖。我们来仔细分析下例子的第一行(译者注:以 CSS 中最长的选择器开始算)。当 id为 ‘original’ 的元素被选中时,找到角色元素里面 data-teams属性包含 ‘original’ 的元素,然后找到它里面的

。2-4行的 ‘force’, ‘factor’, 和 ‘hellfire’ 重复上一步。8-11行继续重复上一步,只不过把

换成了 复选框的 CSS 魔法_html/css_WEB-ITnose

综述

我希望你跟我一样从这些例子中找到了一些乐趣。通过复选框去实现一些好玩的东西,对我而言非常有趣。我并没有排斥在适当的时候使用 JavaScript ,但是没用它也可以实现这么多东西,也是蛮开心的。谢谢阅读!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between an HTML tag and an HTML attribute?What is the difference between an HTML tag and an HTML attribute?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment