css属性选择器的通配符

选择器a[title]还有更多匹配机制a[title='water']

为啥会需要更多匹配机制#

通常用到的css选择器都是精确匹配,在网页开发中需要正确的作用域来区分层次是很合理的。但是在开发完成之后,许多内容都变成了动态可变的。这种时候就需要有更多的匹配机制了。

/* 存在 title 属性的<a> 元素 */
a[title] {
  color: purple;
}

/* 存在 href 属性并且属性值匹配"https://example.org"的<a> 元素 */
a[href="https://example.org"] {
  color: green;
}

/* 存在 href 属性并且属性值包含"example"的<a> 元素 */
a[href*="example"] {
  font-size: 2em;
}

/* 存在 href 属性并且属性值结尾是".org"的<a> 元素 */
a[href$=".org"] {
  font-ze: 2em;
}

/* 存在 href 属性并且属性值开头是"http"的<a> 元素 */
a[href^="http"] {
  fontstyle: italic;
}

/* 存在 class 属性并且属性值包含以空格分隔的"logo"的<a>元素 */
a[class~="logo"] {
  padding: 2px;
}

为了方便理解,下面列一下选择器匹配到的html元素

a[title]

<a title href="#">链接</a>
<a title="链接" href="#">链接</a>
<a title="其他链接" href="#">其他链接</a>

a[href="https://example.org"]

<a title="链接" href="https://example.org">链接</a>

a[href*="example"]

<a title="链接" href="https://example.org">链接</a>
<a title="链接" href="https://example.com">链接</a>
<a title="链接" href="http://www.example.cn">链接</a>
<a title="链接" href="https://thisisexample.org">链接</a>
<a title="链接" href="https://examplelikethis.server.com">链接</a>

a[href$=".org"]

<a title="链接" href="https://example.org">链接</a>
<a title="链接" href="https://g.c.org">链接</a>
<a title="链接" href="http://link.org">链接</a>
<a title="链接" href="//muisc.apple.org">链接</a>

a[href^="http"]

<a title="链接" href="https://g.c.org">链接</a>
<a title="链接" href="http://link.org">链接</a>

a[class~="logo"]

<a title="logo" href="http://link.org" class="logo">logo</a>
<a title="logo" href="http://link.org" class="logo home">logo</a>

相关链接#