.card:has(img) {
border-color: steelblue;
}This matches cards containing an image. Modern browsers support :has(), but always verify the compatibility requirements of your target audience.
Practice Exercise
Build a form and a list of links. Style required fields, email inputs, external HTTPS links, PDF links, and cards containing images using attribute and relational selectors.
Quiz — 10 MCQs
- What does [required] select? (A) Elements with that attribute (B) Only IDs (C) All buttons (D) All links. Answer: A. It tests whether the attribute exists.
- What does [type="email"] match? (A) Exact attribute value email (B) Every input type (C) Email text anywhere on the page (D) An ID named email. Answer: A. The equals operator matches the specified value.
- Which operator matches a value starting with a string? (A) ^= (B) $= (C) *= (D) ~=. Answer: A. The caret-equals operator checks a prefix.
- Which operator matches a suffix? (A) ^= (B) $= (C) |= only (D) ~=. Answer: B. The dollar-equals operator checks the end of a value.
- What does *= mean in an attribute selector? (A) Contains a substring (B) Exact match only (C) Attribute absent (D) Direct child. Answer: A. It checks for a substring.
- What does ~= test? (A) A whitespace-separated word (B) A suffix (C) A child relationship (D) An ID. Answer: A. It matches one word in a space-separated value.
- Which selector has zero specificity? (A) :where(h1, h2) (B) :is(#id) (C) #id (D) .class. Answer: A. The :where() pseudo-class and its argument contribute zero specificity.
- What does :not(:disabled) match on a button? (A) Buttons that do not match :disabled (B) Only disabled buttons (C) All paragraphs (D) Every ID. Answer: A. :not() excludes elements matching its argument.
- What does :has(img) allow you to do? (A) Match an element containing a matching descendant (B) Load an image file (C) Change HTML structure (D) Create an image. Answer: A. It is a relational selector.
- What is the purpose of the i flag in an attribute selector? (A) ASCII case-insensitive matching (B) Add italic styling (C) Select an ID (D) Import CSS. Answer: A. The flag requests case-insensitive attribute-value matching.
Key Takeaways
- Attribute selectors can match presence, exact values, prefixes, suffixes and substrings.
- :is(), :where() and :not() simplify selector logic.
- :has() selects elements based on matching related content.