🔥 $100K Hit! Where Will Bitcoin Go Next? Find Out Live!

Code has been added to clipboard!

Styling Elements According to the CSS ID Selectors

Reading time 2 min
Published Sep 30, 2019
Updated Sep 30, 2019

TL;DR — CSS ID selectors style HTML elements according to their id attribute. ID in CSS is marked by the hash sign (#) similarly to how class selectors have the period.

Matching elements based on ID

The ID selectors in CSS get element by ID attributes. However, the ID selector cannot be used in the document multiple times.

The following example shows the basic use of CSS ID selectors:

Example
#example {
  background-color: lightpink;
  border: solid 2px;
  border-radius: 20px;
  padding: 10px;
  margin: 10px;
}
#example2 {
  background-color: red;
  border: solid 1px green;
  padding: 5px;
  border-radius: 20px;
}

Additionally, you can combine type and ID selectors to style only certain elements with the specified attribute. This example styles the <div> elements with the specified attributes but does not change the <p> element.

Example
div#example {
  background-color: lightpink;
  border: solid 2px;
  border-radius: 20px;
  padding: 10px;
  margin: 10px;
}
div#example2 {
  background-color: red;
  border: solid 1px green;
  padding: 5px;
  border-radius: 20px;
}

DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
edX
Pros
  • A wide range of learning programs
  • University-level courses
  • Easy to navigate
  • Verified certificates
  • Free learning track available
Main Features
  • University-level courses
  • Suitable for enterprises
  • Verified certificates of completion

Overriding styles of other selectors

Styling elements in CSS by ID attributes replace settings of type and class selectors.

Example
#example {
  background-color: lightpink;
  border: solid 2px;
  border-radius: 20px;
  padding: 10px;
  margin: 10px;
}
h1 {
  background-color: red;
  border: solid 1px green;
  padding: 5px;
  border-radius: 20px;
}

Note: the fact that ID in CSS overrides other selectors might cause problems. Therefore, we recommend using class selectors more frequently to avoid issues.

CSS ID: useful tips

  • The ID in CSS only selects the exact matches, meaning that these selectors are case-sensitive.
  • CSS ID selectors must not begin with a number and must contain at least one character.