skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 one body element, so styles are usually applied directly to body rather than a class applied to body.

    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.

    .container {
      padding: 0 10vw;
    }
    <body class="container">
      <div style="background-color: red">
        This div can't fill the body here without more styles
      </div>
      <div style="background-color: lime; margin: 0 -10vw">
        This div can, using negative margin
      </div>
    </body>
    .container {
      padding: 0 10vw;
    }
    <body>
      <div class="container" style="background-color: red">
          By moving the class to a div inside the body, we can have elements stretch the page without resorting to negative margin.
      </div>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search