HTML DIV Containers

<div class="class1">
<div class="class2">
<h1>Random title</h1>
<p>Random words about a random topic</p>
</div>
</div>

I often times see the above yet i do not understand the utility of the div class 2. Often times, this practice is labeled as “containers”. Whats the point of putting a second div if the first div “contains” already all the elements in question?

thanks

Here’s your post as an example.

It’s a set of containers, within a greater container.

There’s a white rectangle, which is a div, then your profile picture, another div, your username, another div, the content of your post, etc.

Dividing a block into different divs allows you to place them where you want them, style them independently of the others, etc.

Hope this makes sense and answers your question?

2 Likes

in my specific example, the first div is containing the second div and everything in the second div (the h1 and p). So i dont see the use of the second div.

Isn’t it redundant ?

Currently having two <div>s may be redundant as you aren’t using them, but as @ghostlovescore said, but it could make a big difference if you has a style sheet applied to the page in terms of selecting elements for placement, color, font family, etc.

For example, suppose you applied this style sheet to your current code:

body {
  background-color: #151515;
}

.class1 {
  margin: 15%;
  height: 100px;
  background-color: #555;
}

.class2 {
  background-color: #56d78e;
  text-align: center;
}

.h1 {
  font-family: Arial, Helvetica, sans-serif;
} 

p {
  background-color: #555;
}

Now you have this:

1 Like

so class 2 overides class 1 which makes it have 2 different colored elements

1 Like

:+1:

Other possibilities could be adding the margin, padding, or border properties, or adding an .onclick or .onhover property in JavaScript.

1 Like