Css Advanced Selectors And Combinators Complete Guide
Understanding the Core Concepts of CSS Advanced Selectors and Combinators
CSS Advanced Selectors and Combinators
Universal Selector (*)
The universal selector represents all elements on the page. It is generally used sparingly due to its broad impact but can be handy for resetting margins and paddings.
* {
margin: 0;
padding: 0;
}
Attribute Selectors
These selectors target elements based on the presence or value of their attributes.
- [attribute] Selects elements with the specified attribute.
[a] {
color: blue;
}
- [attribute=value] Selects elements where the attribute has the specified value.
[type='button'] {
background-color: lightblue;
}
- [attribute~=value] Selects elements where the attribute contains the specified word.
[title~='external'] {
margin-right: 10px;
}
- [attribute|=value] Selects elements where the attribute value is exactly the value specified or starts with the value followed by a hyphen.
[lang|='en'] {
text-align: left;
}
- [attribute^=value] Selects elements where the attribute value starts with the specified value.
[src^='https'] {
background-color: yellow;
}
- [attribute$=value] Selects elements where the attribute value ends with the specified value.
[href$='.pdf'] {
color: green;
}
- [attribute=value]* Selects elements where the attribute value contains the specified substring.
[src*='placeholder'] {
width: 1em;
height: 1em;
}
Pseudo-classes
These selectors are used to define a special state of an element.
- :first-child, :last-child, :nth-child(n) Selects the first, last, or nth child of a parent element.
li:first-child {
font-weight: bold;
}
li:nth-child(2n) {
background: lightgray;
}
- :first-of-type, :last-of-type, :nth-of-type(n) Selects the first, last, or nth child of a parent element of a specific type.
p:first-of-type {
margin-top: 20px;
}
td:nth-of-type(2) {
text-align: right;
}
- :only-child, :only-of-type Selects the element only if it is the only child of a parent element.
span:only-child {
color: red;
}
- :empty Selects elements that have no children.
div:empty {
display: none;
}
- E:enabled, E:disabled Selects input elements that are enabled or disabled.
input:disabled {
background: lightgray;
}
- :checked Selects radio and checkbox input elements that are checked.
input[type='checkbox']:checked {
background: green;
}
Pseudo-elements
These selectors are used to style a specified part of an element.
- ::before, ::after Inserts content before or after the content of a selected element.
p::before {
content: 'Note: ';
font-style: italic;
}
p::after {
content: ' (End of note)';
font-style: italic;
}
- ::first-letter, ::first-line Styles the first letter or line of a block element.
p::first-letter {
font-size: 2em;
font-weight: bold;
}
p::first-line {
text-transform: uppercase;
}
- ::selection Styles the part of an element that is selected by a user.
::selection {
background-color: yellow;
color: black;
}
Combinators
Combinators allow you to combine selectors in order to match elements based on their relationship to other elements.
Descendant Combinator ( )
The descendant combinator selects elements that are descendants of a specified element.
ul li {
margin-top: 5px;
}
Child Combinator (>)
The child combinator selects elements that are direct children of a specified element.
ul > li {
margin-top: 10px;
}
Adjacent Sibling Combinator (+)
The adjacent sibling combinator selects the next sibling of an element if it is the same type.
h2 + p {
font-size: 18px;
}
General Sibling Combinator (~)
The general sibling combinator selects all siblings that come after a specified element.
Online Code run
Step-by-Step Guide: How to Implement CSS Advanced Selectors and Combinators
Example 1: Child Selector (>
)
The child selector targets elements that are direct children of a specified parent element.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>CSS Child Selector</title>
</head>
<body>
<div class="parent">
<p>This is a paragraph inside the parent div.</p>
<ul>
<li>This is a list item inside a ul inside the parent div.</li>
<li>Another list item</li>
</ul>
<div class="child">
<p>This is a paragraph inside a child div inside the parent div.</p>
</div>
</div>
</body>
</html>
CSS (styles.css):
.parent > p {
color: blue;
}
.parent > div p {
color: green;
}
Explanation:
- The first rule
.parent > p
will target only the<p>
elements that are direct children of.parent
. - The second rule
.parent > div p
targets<p>
elements but only if they are inside a<div>
which is a direct child of.parent
.
Example 2: Adjacent Sibling Selector (+
)
The adjacent sibling selector targets an element that directly follows another element.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>CSS Adjacent Sibling Selector</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This paragraph will be styled because it follows the heading.</p>
<p>This paragraph will not be styled.</p>
</body>
</html>
CSS (styles.css):
h1 + p {
font-weight: bold;
}
Explanation:
- The rule
h1 + p
will style the first<p>
element that immediately follows an<h1>
element.
Example 3: General Sibling Selector (~
)
The general sibling selector targets all elements that follow another element, but they don’t have to be immediately adjacent.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>CSS General Sibling Selector</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This paragraph will be styled because it follows the heading.</p>
<p>This paragraph will also be styled.</p>
<div>This div will not be styled.</div>
<p>This paragraph will be styled as well.</p>
</body>
</html>
CSS (styles.css):
h1 ~ p {
font-style: italic;
}
Explanation:
- The rule
h1 ~ p
will style all<p>
elements that follow an<h1>
element, regardless of how many other elements are in between.
Example 4: Descendant Combinator
The descendant combinator (space) targets all elements at any level of nesting within a parent element.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>CSS Descendant Combinator</title>
</head>
<body>
<div class="ancestor">
<p>This paragraph is a direct descendant and will be styled.</p>
<ul>
<li><p>This paragraph is not a direct descendant but will still be styled.</p></li>
</ul>
</div>
</body>
</html>
CSS (styles.css):
.ancestor p {
color: orange;
}
Explanation:
- The rule
.ancestor p
will style all<p>
elements that are descendants of the.ancestor
div, even if they are nested within another element.
Example 5: Attribute Selector
Attribute selectors allow you to select elements based on the presence or value of an HTML attribute.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>CSS Attribute Selector</title>
</head>
<body>
<a href="https://www.example.com">Visit Example</a>
<a href="https://www.google.com">Visit Google</a>
<a href="https://www.facebook.com" target="_blank">Visit Facebook</a>
</body>
</html>
CSS (styles.css):
a[href*="google"] {
text-decoration: none;
}
a[target] {
color: purple;
}
Explanation:
- The first rule
a[href*="google"]
will style anchor tags where thehref
attribute contains the substring "google". - The second rule
a[target]
will style anchor tags that have atarget
attribute, regardless of its value.
Top 10 Interview Questions & Answers on CSS Advanced Selectors and Combinators
1. What is the difference between ::before
and ::after
pseudo-elements?
Answer:
The ::before
and ::after
pseudo-elements in CSS are used to insert content before or after the content of an element, respectively. They are often used alongside the content
property to add decorative elements or text without changing the HTML structure. For example:
div::before {
content: "Start: ";
color: red;
}
div::after {
content: " - End";
color: blue;
}
In this case, the text "Start: " will appear before any content inside the <div>
, and " - End" will appear after it.
2. How do you use attribute selectors in CSS?
Answer:
Attribute selectors target elements based on the presence or value of an attribute. Common types include:
[attr]
: Selects elements with the specified attribute.[attr=value]
: Selects elements whose attribute has exactly that value.[attr~="value"]
: Selects elements whose attribute contains that word (separated by spaces).[attr*="value"]
: Selects elements whose attribute contains that substring anywhere within.[attr|="value"]
: Selects elements whose attribute starts with that value (typically used for language attributes likelang
).
Example:
a[href*="example.com"] {
background-color: yellow;
}
/* Applies yellow background to links whose href includes "example.com". */
3. Can you explain the difference between >
(child combinator) and +
(adjacent sibling combinator)?
Answer:
- The
>
child combinator selects only those elements that are direct children of another element. - The
+
adjacent sibling combinator targets elements that immediately follow a sibling with a specific selector within the same parent.
Examples:
ul > li { color: green; }
/* Only immediate <li> children of <ul> get green color. */
h1 + p { font-size: 20px; }
/* This sets the font size of the paragraph directly following an h1 heading to 20px but not other paragraphs. */
4. What is a descendant combinator, and how does it differ from a child combinator?
Answer:
The descendant combinator (
—a space between two selectors) matches elements that are descendants of another specified element, including indirect descendants. In contrast, the child combinator (>
) only selects direct children.
Example:
div p { color: orange; }
/* Any <p> inside a <div>, no matter how deep, gets an orange color. */
div > p { color: yellow; }
/* Only direct <p> children of <div> get yellow color. Other nested paragraphs are unaffected. */
5. How do you use :nth-child()
and :nth-of-type()
pseudo-classes?
Answer:
:nth-child(n)
targets every nth child of a parent element regardless of its type.:nth-of-type(n)
targets every nth element of its type among siblings.
Examples:
li:nth-child(2) { color: purple; }
/* Styles will apply to every second <li> element in a list, even if non-li siblings exist. */
p:nth-of-type(3) { color: blue; }
/* Styles will be applied to every third <p> among its siblings (other <p>s), ignoring other types of siblings. */
6. What does the universal selector *
do in CSS, and when should you use it?
Answer:
The universal selector *
selects all elements within the document. While it can reset or apply styles universally, frequent use is discouraged because it can cause performance issues and make code harder to manage. It may be useful sparingly for applying baseline styles universally:
* { margin: 0; padding: 0; box-sizing: border-box; }
/* Resets margins and paddings, ensures consistent sizing among elements. */
7. Explain how CSS :not()
pseudo-class works and provide examples.
Answer:
The :not()
pseudo-class is used to select the elements that do not match the given criteria within the parentheses.
Example:
p:not(.intro) { color: gray; }
/* Styles all paragraphs except the one(s) with the class 'intro'. */
input:not([type='checkbox']) { width: 200px; }
/* Styles all inputs except those of type checkbox, setting their width to 200px. */
8. How can CSS custom properties (variables) be used within selectors for conditional styling?
Answer:
Technically, CSS variables aren't natively integrated into selectors themselves. However, they can be used within media queries to dynamically adjust layout breakpoints, or programmatically set classes on the root element and style based on those variables indirectly.
Example using dynamic breakpoints:
:root { --small-screen: 767px; }
@media (max-width: var(--small-screen)) {
.container {
width: 100%;
flex-direction: column;
}
button {
display: block;
width: 100%;
}
}
In this context, CSS variables are helpful to maintain consistency across various media queries.
9. What is a pseudo-class and list some advanced pseudo-classes used in CSS?
Answer:
Pseudo-classes start with :
and select elements based on their state. Some advanced pseudo-classes:
:focus-within
: Matches an element if it or its descendants have focus.:last-child
: Matches the last child of its parent.:first-of-type()
: Matches the first element of its type among siblings.:hover
: Changes styling when the user hovers over an element.:active
: Applies styles while an element is being activated by the user.:checked
: Matches radio buttons or checkboxes that are checked.:disabled
: Matches form controls that are disabled.:empty
: Matches elements that contain no content or white space.:nth-last-child(n)
: Matches nth-to-last child of their parent.
Example:
div:focus-within { outline: 2px solid red; }
/* Adds a red outline around a div when any of its children is focused (e.g., form input). */
10. How do you cascade multiple pseudo-classes together?
Answer:
Multiple pseudo-classes can be combined to refine selections further. They must be placed after the simple selectors. The order of pseudo-classes matters as it describes a sequence of states or conditions.
Example:
button:enabled:hover {
background-color: blue;
cursor: pointer;
}
/* Styles are only applied to enabled buttons when hovered over, making these buttons visually distinct. */
In this example, the button will only take the specified styles if it's both enabled and hovered over by the user. Cascading allows complex and specific styling rules without needing additional markup or JavaScript manipulation.
Login to post a comment.