Combinators and Attribute Selectors
What Is It?
Combinators select elements by their relationships. Attribute selectors match HTML attributes and, optionally, their values.
Properties, Tags and Attributes Explained
.panel p: Matches any paragraph inside .panel..panel > p: Matches only direct paragraph children.label + input: Matches an input immediately following a label with the same parent.[type="email"]: Matches an element whose type attribute is email.
Each example is a complete HTML page. The CSS is inside the head's style element. Use Try in new tab to edit the CSS or HTML, run your changes, and reset the example.
Example 1: Direct children
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Combinators and Attribute Selectors</title>
<style>
.panel > p { background: #dcfce7; padding: 8px; }
</style>
</head>
<body>
<div class="panel"><p>Direct child</p><section><p>Nested paragraph</p></section></div>
</body>
</html>Browser preview
What you see: Only the direct paragraph child has a green background.
Example 2: Attribute matching
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Combinators and Attribute Selectors</title>
<style>
input[type="email"] { border: 2px solid #2563eb; padding: 8px; }
</style>
</head>
<body>
<label for="email">Email</label> <input id="email" type="email" placeholder="you@example.com">
</body>
</html>Browser preview
What you see: The email input receives the blue border. The label for attribute connects to the input id.
When and Where to Use It
Use relationships to style a component area and attributes to target input types or states without adding extra classes.
Common Mistake or Useful Tip
Keep selectors short; deeply nested selectors become fragile when the HTML changes.
Try It Yourself
Add a text input and check that the email-only rule does not style it.