Hilow
Hilow

Reputation: 61

Correct usage of HTML Semantic Elements

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 class="info">
        ...

or like that :

<section class="info">
        ...

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

Another example would be the header element :

<body>
    <header>
      <div class="logo">
        ...

or should I directly start with

<body>
    <header class="logo">
        ...

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.

Upvotes: 1

Views: 800

Answers (4)

budi.sann
budi.sann

Reputation: 80

Both are fine. but if i should read other people code i prefer code like this one.

<body>
<header class="logo">

To read second code,

<section>
  <div class="info">
    ...

you need to carefully scan for the class names, picking them out from between the boilerplate. And once you're a few levels deep in the markup, it becomes tricky to keep track of which closing tags go with which <div...> opening tags

Upvotes: 4

offkee
offkee

Reputation: 11

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.

Upvotes: 1

Danyal Chatha
Danyal Chatha

Reputation: 15

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

<section>
  <div class="info">
    <h1>Information</h1>
  </div>
</section>

Upvotes: 1

Sunil Kumar Das
Sunil Kumar Das

Reputation: 419

Both are fine. It comes to personal preferences.

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

Upvotes: 1

Related Questions