Skip to content Skip to sidebar Skip to footer

Is It Right To Add Style In Css To Semantic Elements Of HTML 5?

Is it right, to add styles to html 5 semantics (nav, header, footer, etc...) like we add them to divs? To use them instead of regular divs? One time I heard frome someone I respect

Solution 1:

The idea of separating the structure/content (you html code) from your style gives you exactly this ability, and actually drives you in this direction.

The structure gives multiple devices the ability to better understand your content in order to give your users a better experience. For example - if you will just use a ul > li structure for your menu, some devices that are not regular browsers will not be able to fully understand that this is the menu for your website, while using nav > ul > li gives them exactly that.

The style only tells the device how it should display them - and you should use it in order to give your users better experience.

The semantic elements helps us separate the structure of the page, for example:

enter image description here


Solution 2:

Well, HTML5 semantic (nav, header, footer, etc...) were created to help us give meaningful and self-descriptive names to sections of our web pages. They are expected to be unique.

So, before the introduction of these semantics, sections were done this way:

<div id="main-section">
  your content
</div>
<div id="sidebar">
  your sidebar content
</div>

HTML5 semantics were supposed to save us from situations like the above while also being descriptive.

Styles were added to sections like the above then, and I don't see why we can't do the same now. There isn't really any rule against adding styles to HTML5 semantics but ensure that HTML5 semantics are used for unique elements in the first place.


Solution 3:

I agree. Avoid adding styles to semantic elements. This is because these elements add nothing new when we are speaking about how things 'look'.

Remember that you want to avoid redundancy. If you need a block element, you are thinking about the 'look', and so use a div and style that. Then immediately inside that div, add your semantic element if you wish. Leave the semantic elements as hidden as possible from your css, and even from your selectors, whether in the css, or the javascript. However, adding a custom class that marks these semantic elements is good for clarity. And so, instead of:

div > * h1,

you would write like this:

div > .semanticElement h1. 

This should be better for clarity, while avoiding referencing the semantic element.

If the reason for some of the above is not clear, think of it this way. The semantic changes for one element, and now suddenly I also have to make a change in the css and javascript, which is absurd.


Post a Comment for "Is It Right To Add Style In Css To Semantic Elements Of HTML 5?"