CSS选择器是前端开发中精准控制元素样式的关键工具。以下是几种主要的精准控制方法:
p { color: red; }
- 选择所有<p>
元素.warning { color: yellow; }
- 选择所有class包含"warning"的元素#header { height: 100px; }
- 选择id为"header"的元素div p { color: blue; }
- 选择div内的所有p元素ul > li { list-style: none; }
- 只选择ul的直接子元素lih1 + p { margin-top: 0; }
- 选择紧接在h1后的p元素h2 ~ p { color: green; }
- 选择h2之后的所有同级p元素[type="text"] { border: 1px solid #ccc; }
- 选择type属性为text的元素[href^="https"]
- 选择href属性以"https"开头的元素[href$=".pdf"]
- 选择href属性以".pdf"结尾的元素[class*="btn"]
- 选择class属性包含"btn"的元素a:hover { color: orange; }
- 鼠标悬停时的样式li:nth-child(odd)
- 选择奇数位置的li元素input:focus
- 选择获得焦点的输入元素:not(.hidden)
- 选择不包含hidden类的元素p::first-line
- 选择p元素的第一行p::first-letter
- 选择p元素的首字母::before
和 ::after
- 在元素前后插入内容color: red !important;
(慎用):root { --main-color: #06c; }
然后 color: var(--main-color);
通过合理组合这些选择器和方法,可以实现对页面元素的精准样式控制。