HTML CSS 属性选择器

我们可以设置带有特定属性或属性值的 HTML 元素的样式。

CSS [attribute] 选择器

在 HTML 中所有带有指定属性的元素显示改CSS样式,例如:

<style>
a[target] {
  background-color: yellow;
}
</style>

<p>带有 target 属性的链接获得颜色背景:</p>

<a href="http://www.zhuei.com" target="_blank">ZHUEi.COM</a>
<a href="http://www.zhuei.net" target="_top">ZHUEi.NET</a>

CSS [attribute=”value”] 选择器

在 HTML 中所有带有指定属性和值的元素显示改CSS样式,例如:

<style>
a[target=_blank] {
  background-color: yellow;
}
</style>

<p>带有 target 属性值为 _blank 的链接获得颜色背景:</p>

<a href="http://www.zhuei.com" target="_blank">ZHUEi.COM</a>
<a href="http://www.zhuei.net" target="_top">ZHUEi.NET</a>

CSS [attribute~=”value”] 选择器

在 HTML 中所有包含指定属性和值的元素显示改CSS样式,例如:

<style>
[title~=flower] {
  border: 5px solid yellow;
}
</style>

<p>title 属性包含 "flower" 的所有图像会有黄色边框。</p>
<img src="/img.jpg" title="look flower">
<img src="/img.gif" title="flower">

CSS [attribute|=”value”] 选择器

在 HTML 中所有选取指定属性以指定值开头的元素显示改CSS样式,例如:

<style>
[class|=top] {
  background: yellow;
}
</style>
<h1 class="top-header">Welcome</h1>
<p class="top-text">Hello world!</p>
<p class="topcontent">ZHUEi.COM</p>

CSS [attribute^=”value”] 选择器

在 HTML 中所有选取指定属性以指定值开头的元素显示改CSS样式,例如:

<style>
[class^="top"] {
  background: yellow;
}
</style>

<h1 class="top-header">Welcome</h1>
<p class="top-text">Hello world!</p>

<p class="topcontent">ZHUEi.COM</p>

CSS [attribute$=”value”] 选择器

在 HTML 中所有选取属性值包含指定词的元素显示改CSS样式,例如:

<style> 
[class*="te"] {
  background: yellow;
}
</style>
<div class="first_test">The first div element.</div>
<div class="second">The second div element.</div>
<div class="my-test">The third div element.</div>
<p class="mytest">This is some text in a paragraph.</p>

设置表单样式
若需为不带 class 或 id 的表单设置样式,属性选择器会很有用,例如:

<style>
input[type=text] {
  width: 150px;
  display: block;
  margin-bottom: 10px;
  background-color: yellow;
}

input[type=button] {
  width: 120px;
  margin-left: 35px;
  display: block;
}
</style>
<form name="input" action="" method="get">
  Firstname:<input type="text" name="Name" value="Bill" size="20">
  Lastname:<input type="text" name="Name" value="Gates" size="20">
  <input type="button" value="Example Button">
</form>

所有 CSS 属性选择器

选择器例子例子描述
[attribute][target]选择带有 target 属性的所有元素。
[attribute=value][target=_blank]选择带有 target=”_blank” 属性的所有元素。
[attribute~=value][title~=flower]选择带有包含 “flower” 一词的 title 属性的所有元素。
[attribute|=value][lang|=en]选择带有以 “en” 开头的 lang 属性的所有元素。
[attribute^=value]a[href^=”https”]选择其 href 属性值以 “https” 开头的每个 <a> 元素。
[attribute$=value]a[href$=”.pdf”]选择其 href 属性值以 “.pdf” 结尾的每个 <a> 元素。
[attribute*=value]a[href*=”ZHUEi”]选择其 href 属性值包含子串 “ZHUEi” 的每个 <a> 元素。

如果你发现错误或有其他见解,请给www.zhuei.com留言,我们会尽快更新本文!

发表评论

邮箱地址不会被公开。 必填项已用*标注