¥Styling radio inputs
以下示例显示了我们在整篇文章中看到的示例的稍微更彻底的版本,具有一些附加样式,并通过使用专用元素建立了更好的语义。HTML 看起来像这样:
¥The following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements. The HTML looks like this:
html
这个例子中涉及到的 CSS 比较重要一点:
¥The CSS involved in this example is a bit more significant:
csshtml {
font-family: sans-serif;
}
div:first-of-type {
display: flex;
align-items: flex-start;
margin-bottom: 5px;
}
label {
margin-right: 15px;
line-height: 32px;
}
input {
appearance: none;
border-radius: 50%;
width: 16px;
height: 16px;
border: 2px solid #999;
transition: 0.2s all linear;
margin-right: 5px;
position: relative;
top: 4px;
}
input:checked {
border: 6px solid black;
}
button,
legend {
color: white;
background-color: black;
padding: 5px 10px;
border-radius: 0;
border: 0;
font-size: 14px;
}
button:hover,
button:focus {
color: #999;
}
button:active {
background-color: white;
color: black;
outline: 1px solid black;
}
这里最值得注意的是 appearance 属性的使用(带有支持某些浏览器所需的前缀)。默认情况下,单选按钮(和 checkboxes)的样式采用操作系统这些控件的原生样式。通过指定 appearance: none,你可以完全删除原生样式,并为它们创建你自己的样式。在这里,我们使用 border 以及 border-radius 和 transition 来创建一个漂亮的动画单选框选择。另请注意 :checked 伪类如何用于指定单选按钮被选中时的外观样式。
¥Most notable here is the use of the appearance property (with prefixes needed to support some browsers). By default, radio buttons (and checkboxes) are styled with the operating system's native styles for those controls. By specifying appearance: none, you can remove the native styling altogether, and create your own styles for them. Here we've used a border along with border-radius and a transition to create a nice animating radio selection. Notice also how the :checked pseudo-class is used to specify the styles for the radio button's appearance when selected.
注意:如果你想使用 appearance 属性,你应该非常仔细地测试它。尽管大多数现代浏览器都支持它,但其实现差异很大。在较旧的浏览器中,即使是关键字 none 在不同浏览器之间的效果也不尽相同,有些浏览器根本不支持。在最新的浏览器中差异较小。
¥Note: If you wish to use the appearance property, you should test it very carefully. Although it is supported in most modern browsers, its implementation varies widely. In older browsers, even the keyword none does not have the same effect across different browsers, and some do not support it at all. The differences are smaller in the newest browsers.
请注意,单击单选按钮时,随着两个按钮更改状态,会出现良好、平滑的淡出/淡入效果。此外,图例和提交按钮的样式和颜色都经过定制,具有强烈的对比度。这可能不是你在真正的 Web 应用中想要的外观,但它确实展示了可能性。
¥Notice that when clicking on a radio button, there's a nice, smooth fade out/in effect as the two buttons change state. In addition, the style and coloring of the legend and submit button are customized to have strong contrast. This might not be a look you'd want in a real web application, but it definitely shows off the possibilities.
" class="article-image">