Reputation: 3
i am a beginner in html and css could anyone please tell me the difference between these 2 codes , i am getting the same result in both of them. i mean is there any difference between putting classes in div tag & putting them directly in h1 tag.
CODE 1
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
text-align:center;
color:white;
}
.box {
height:55px;
weight:55px;
border:3px;
border-raduis:5px;
background-color:#000000;
}
</style>
</head>
<body>
<div class='box'>
<h1>
main text
</h1>
</div>
</body>
<html>
CODE 2
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
text-align:center;
color:white;
}
.box {
height:55px;
weight:55px;
border:3px;
border-raduis:5px;
background-color:#000000;
}
</style>
</head>
<body>
<h1 class='box'>
main text
</h1>
</body>
<html>
in both codes i get the same main text inside the box so does it mean that class in div tag is doing the same thing what class in h1 tag is doing?
Upvotes: 0
Views: 815
Reputation: 901
does it mean that class in div tag is doing the same thing what class in h1 tag is doing?
In this case yes, but not necessarily. The second example is better. If you want to make sure you are only applying styles to the heading, apply it to the heading, not the parent element (the div in this case). For instance, what if the div contained a P element as well? In the first example, the H1 and P elements would have a red background since the parent block-level element has a red background. In the second example, only the H1 element would have a red background.
On more complicated projects, like an existing website, there will often be existing stylesheets that you wish to override. Always apply styles to the closest element, or the exact element you wish to style. Also browsers have built in styles for common elements like headings, tables etc. Try using no CSS whatsoever and view the difference between H1 and P elements. Different browsers will apply their own styles, so a common practice is to apply a set of styles to "reset" or override the browser styles. (Another example is making a page with red background for HTML and black for BODY. Look at the browser-defined margins.)
Finally, another approach to only control the H1 element if it is inside a DIV with a class of "box" would be this CSS:
.box h1 {
height:55px;
weight:55px;
border:3px;
border-raduis:5px;
background-color:#000000;
}
Upvotes: 1
Reputation: 135
the output is both codes are the same. but there is no technical difference just the second code is using extra div
Upvotes: 0