Selecting Elements in CSS Using Selectors

css selector guide
10 November 2024

Why are selectors important?

One of the fundamental principles in web design is the precise selection of elements for styling, which is accomplished with the help of CSS selectors. CSS selectors are powerful tools for applying CSS rules to specific parts of an HTML document. The correct use of these selectors can help us achieve better management and more effective styles.

Type and class selectors

Type and class selectors are among the most common and basic methods of selecting elements. Type selectors can function based on the type of HTML tag (like <div>, <p>) and are very easy to use. Conversely, class selectors, which start with a dot (.), allow you to select multiple elements with a shared class name, enhancing styling capabilities.

ID selectors

ID selectors are another way of selecting elements in CSS that can uniquely identify a single element on a page. They start with the # symbol, and due to being faster compared to classes, they are usually used to select a unique element in the document.

Combination of selectors

Combining selectors provides a more specific method for accurately selecting elements. You can combine type, class, and ID selectors to create more intricate combinations for selecting elements. This approach aids in better code organization and functionality improvement in design.


  /* Type selectors */
  h1 {
    color: blue;
  }
  
  /* Class selectors */
  .highlight {
    background-color: yellow;
  }
  
  /* ID selectors */
  #main-header {
    font-size: 24px;
  }
  
  /* Combining selectors */
  div.highlight {
    border: 1px solid red;
  }
  

Line by line code explanation

h1 { color: blue; }: This line changes the color of all <h1> tags to blue using a type selector.

.highlight { background-color: yellow; }: This line sets the background color to yellow for any element that has the class highlight.

#main-header { font-size: 24px; }: This line changes the font size of the unique element with the ID main-header to 24 pixels.

div.highlight { border: 1px solid red; }: This line adds a red border to all <div> elements that have the class highlight.

FAQ

?

How can I select only one specific element with CSS?

?

What is the difference between class and ID selectors?

?

Can I combine multiple selectors together?