CSS ID and Class

The id selector is marked with a hash in CSS (#id_name) and the class selector with a dot (.class_name).

The id selector can only be used once on a page – it is useful to directly target an individual element. For example a logo at the top of the page that only appears once could be targeted by putting an id attribute inside the HTML tag.

HTML:
<header id="logo"><img src="./SVG/logo.svg" alt="Company logo"></header>

CSS:
#id { padding: 1em; }

 

The class selector is the same use of class as many other languages, it allows you to set attributes for a group or type of objects. You can apply class selectors to as many elements on a page as you like.

HTML:
<p class="box">Paragraph</p>
<aside class="box">Text</aside>
CSS:
.box { color:#330033; }

 

You can apply a class and an id to the same element:

<p class="box" id="logo">Text</p>

You can also apply multiple classes:

<p class="box class2 class3" id="logo">Text</p>

 

Mozilla Developer Network. (2017). ID selectors. [online] Available at: https://developer.mozilla.org/en-US/docs/Web/CSS/ID_selectors [Accessed 2 Dec. 2017].

StackOverflow. (2017). Can an element have both an id and a class?. [online] Stackoverflow.com. Available at: https://stackoverflow.com/questions/2813653/can-an-element-have-both-an-id-and-a-class [Accessed 18 Dec. 2017].


References

Please find all references here.

Leave a Reply