Dan Dan - 5 months ago 8
CSS Question

Using <div> as a parent element

I have recently been following tutorials on html and css. In a lot of these tutorials I see people using tags, such as

<nav>
,
<footer>
, etc..., like this.

<someTag class = "someClass">
<div class = "anotherClass">
<whatever>

</whatever>
</div>
</someTag>


However is it not better practice to do something similar to this?

<someTag class = "someClass">
<whatever class = "anotherClass">

</whatever>
</someTag>


My question is why do people use divs in situations like this at all?

Answer

HTML standard defines a set of allowed elements, including NAV, FOOTER, DIV, etc.

Arbitrary custom elements are disallowed. You can use them technically, but such HTML document would be formally invalid and potentially not future-proof since there is a probability that your custom elements may be added to the standard in future.

DIV is a common container without semantic meaning and should generally be used just to group other elements to apply styles.

Whether to apply styles directly to DIV or to elements it contains, depends on specific situation. If it was needed to define a golden rule, it would probably be something like this:

DIV should contain at least one descendant level marked-up as a semantic (i. e. not DIV or SPAN) element.

If a DIV contains just inline elements or pure text, this typically indicates that markup is wrong.