Home > Net >  how to set body width and center it horizontally
how to set body width and center it horizontally

Time:12-16

I remember - it was possible earlier - to set body width and center it horizontally - like in the example below
now - seems it is not possible this way
how to do it ?

body{
  width: 99px;
  margin: 0 auto;
  height: 100vh;
  background: orange;
}

CodePudding user response:

Use a container element and set a specific max-width. A common width many websites use is 960px. To actually center the page, add margin: auto.

The following example will center the website on screens that are wider than 500px. On screens that are less than 500px wide, it will span the whole of the page:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
  background: #555;
}

.content {
  max-width: 500px;
  margin: auto;
  background: white;
  padding: 10px;
}
</style>
</head>
<body>

<div >
  <h1>This page is horizontally centered on screens that are wider than 500 pixels.</h1>
  <h1>Resize the browser window to see the effect.</h1>
  <p>This page is always centered on screens that are wider than 500px. On screens that are less than 
  500px wide, it will span the whole of the page.</p>
  <p>Content inside this container is centered horizontally.</p>
 </div>

</body>
</html>

CodePudding user response:

The body is already 99px wide and centered horizontally. However, if you want the background color to appear only at the width, I suggest you use the :before pseudo selector like this:

body{
  position: relative;
  width: 99px;
  margin: 0 auto;
  height: 100vh;
}

body:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color :orange;
  z-index: -1;
}
<h2>Some content here</h2>

  • Related