Home > database >  Correct usage of HTML Semantic Elements
Correct usage of HTML Semantic Elements

Time:11-18

I was wondering what's the "best" or most common way to use semantic elements in HTML. I know what they are and what they do, but should I use them like that :

<section>
      <div >
        ...

or like that :

<section >
        ...

Is it wrong to use one or another ? Are both actually "valid" ?

Another example would be the header element :

<body>
    <header>
      <div >
        ...

or should I directly start with

<body>
    <header >
        ...

Maybe this question might sound strange for advanced developers but for a beginner it might not be obvious and I didn't really find a clear answer.

I'm personally using the "long" version and started questioning myself when I started looking at other people's codes.

CodePudding user response:

Both are fine. It comes to personal preferences.

The technical aspect is that it will add a bit of padding between two nested elements.

CodePudding user response:

I prefer to go with the first one as it seems more organized, but honestly, it just preferences.

<section>
  <div >
    <h1>Information</h1>
  </div>
</section>

CodePudding user response:

Both are valid. When using semantic HTML, the tag should be able to give you some context for what is happening. I prefer structuring my pages like this:

<section class=blogPost>
<!-- section acts as a container for content -->
<h1>Introduction to HTML</h1>
<p> blah blah blah blah </p>
<!-- h1 and p are the actual content -->
</section>

You can use classes for each tag in your HTML file for increased semantics by using microformats, though semantic tags usually just mean you try to use specific tags instead of unspecified tags such as div or span. I would say that you should try to limit the number of tags used if possible because adding a div tag just to give it a class will end up confusing you even more, especially if you can just put your content in your header or section tags directly.

  • Related