What is the difference between ids and classes?

Both are used to assign certain styles to an element. The difference is that an ID is unique and should only be used once on every page, whereas a class can be used multiple times.

A good example is, say you have a header, a content area, a sidebar, and a footer. These should all be defined as an id as they are only used once on your page. You can then use the CSS to define things like widths, background colors and what not. Now if you want to add a border to all of these sections, you are able to assign a border class to the elements as well, and then define what you want the border to look like in the css. That way, they all have the same border, and you would only have to change the css in one place!

HTML

<body>
  <header class="border" id="header">HEADER</header>
  <main class="border" id="main">MAIN CONTENT</main>
  <aside class="border" id="sidebar">SIDEBAR</aside>
  <footer class="border" id="footer">FOOTER</footer>
</body>

CSS

body {
  font-family: sans-serif;
}

#header {
  background: pink;
  padding: 30px;
  margin: 0 5px;
}

#main {
  background: lightblue;
  padding: 30px;
  margin: 10px 5px;
  width: 68%;
  float: left;
}

#sidebar {
  background: mediumspringgreen;
  padding: 30px;
  margin: 10px 5px;
  width: 30%;
  float: right;
}

#footer {
  background: orangered;
  padding: 30px;
  margin: 10px 5px;
  clear: both;
}

.border {
  border: solid 4px #abc;
}
<br>

Still need help? Contact Us Contact Us