🎯

How to Use CSS Selectors

HTML/CSSBeginner

Master different CSS selector types to target HTML elements.

Code Example

HTML/CSS
<!DOCTYPE html>
<html>
<head>
  <title>CSS Selectors</title>
  <style>
    /* Element selector */
    p { color: blue; }
    
    /* Class selector */
    .highlight { background: yellow; }
    
    /* ID selector */
    #special { font-weight: bold; }
    
    /* Descendant selector */
    article p { font-size: 16px; }
    
    /* Child selector */
    ul > li { margin: 5px 0; }
    
    /* Adjacent sibling */
    h2 + p { color: green; }
    
    /* Attribute selector */
    input[type="text"] { border: 2px solid blue; }
    
    /* Pseudo-class */
    a:hover { color: red; }
    
    /* Pseudo-element */
    p::first-line { font-weight: bold; }
    
    /* Multiple selectors */
    h1, h2, h3 { font-family: Arial; }
    
    /* Universal selector */
    * { box-sizing: border-box; }
  </style>
</head>
<body>
  <h1>CSS Selectors Demo</h1>
  
  <p class="highlight">This paragraph has a class.</p>
  <p id="special">This paragraph has an ID.</p>
  
  <article>
    <h2>Article Title</h2>
    <p>This paragraph is inside an article.</p>
  </article>
  
  <ul>
    <li>First item</li>
    <li>Second item</li>
    <li>Third item</li>
  </ul>
  
  <h2>Next Heading</h2>
  <p>This paragraph follows an h2.</p>
  
  <input type="text" placeholder="Text input">
  <input type="email" placeholder="Email input">
  
  <a href="#">Hover over me</a>
</body>
</html>

Explanation

CSS selectors target HTML elements. Element selectors (p), class (.name), ID (#name), descendants (div p), children (div > p), attributes ([type="text"]), pseudo-classes (:hover), and pseudo-elements (::first-line).

Related Tutorials