Classes & IDs (HTML/CSS/JS)

Target Content with Classes and Id

By assigning a class or id to an HTML element you can apply specific styles in a targeted way.

HTML
<div class="card" id="jill-card">Jill - Data Scientist</div>
<div class="card">Johnny - UX Designer</div>
<div class="card">Mia - Software Developer</div>
<div>Patrick - Business Analyst</div>
CSS
.card {
  padding: 5px;
  margin: 20px;
  background-color: lightgray;
  box-shadow: 2px 2px 3px;
}
#jill-card {
  background: yellow;
}

Try it out

  1. Copy the HTML and CSS above and paste it in a new CodePen.

  2. Take a look at the browser preview and try to decipher what is going on.

  3. Notice how assigning id="jill-card" in the HTML allows the element to be "targeted" with the CSS selector #jill-card.

  4. Notice how assigning class="card" in the HTML allows several elements to be "targeted" with the CSS selector .card.

  5. Go ahead and give Patrick's text a class of "card" and then add a unique id to his HTML element and some CSS to make his card stand out from all the others.

id - An HTML id is selected in CSS with a # prefix and should be used to target a single element on a page.

class - An HTML class is selected in CSS with a . prefix and can be used to select several elements that will share a common style.

Last updated