Should I use
<body> , <div class="container"> or <body class="container">
Is there some instance of CSS I can write that makes one preferable over the other?
I tried these
.container {
width: 80vw;
margin: 0 auto;
margin-top: 3vh;
}
body {
width: 80vw;
margin: 0 auto;
margin-top: 3vh;
}
but the result was the same
2
Answers
There’s nothing wrong with styling the
<body>
directly per se. However one reason I can think of styling a<div>
instead of the<body>
is if you plan on swapping out the container<div>
with another [differently] styled<div>
with JavaScript. There are no absolute right or wrong ways to use CSS, only "more right" and "more wrong" ways, and in this specific situation it’s just preference.For example, inline CSS versus CSS located in stylesheets debate…there are many situations where it’s recommended to use inline CSS instead of putting it in a stylesheet (such as when an element needs an extremely specific style that will only exist in one place in your application). Do what is most scalable and understandable for you now and you will learn along the way why people do what they do with CSS.
There’s no reason you can’t add classes to the
body
, but generally you don’t see this because documents will only every have onebody
element, so styles are usually applied directly tobody
rather than a class applied tobody
.In the case of a bootstrap
container
, if you make the body a container, you won’t be able to easily create elements that extend the full width of the page, and you’d have to use negative width, positioning changes, or other stylings to get the element to extend past it’s parent.