Attribute Selectors
Square brackets allow you to select elements with particular
attributes or attribute values. For example, this rule hides all
step elements that have an
optional attribute:
step[optional] {display: none}This rule hides all elements that have an optional attribute regardless of the
element’s name:
*[optional] {display: none}An equals sign selects an element by a given
attribute’s value. For example, this rule hides all step elements that have an optional attribute with the value yes:
step[optional="yes"] {display: none}The ~= operator selects elements that contain a given word as
part of the value of a specified attribute. The word must be
complete and separated from other words in the attribute value by
whitespace, as in a NMTOKENS
attribute. That is, this is not a substring match. For example, this
rule makes bold all recipe
elements whose source attribute
contains the word “Anderson”:
recipe[source~="Anderson"] {font-weight: bold}Finally, the |= operator matches against the first word in a
hyphen-separated attribute value, such as Anderson-Harold or fr-CA.
CSS also provides a special syntax for selecting elements with
a given ID value, even when you don’t know exactly the name of the
ID type attribute. Simply separate the ID from the element name with
a sharp sign (#). For
example, this rule applies to the single step element whose ID type attribute has
the value P833:
step#P833 { font-weight: 800 }Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access