1

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;
}
Raptor
  • 53,206
  • 45
  • 230
  • 366
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 1
    Good news, you've already succeeded. If you put some content in the body you'll see. – Alohci Dec 16 '21 at 00:37
  • @Alohci - it doesn't work. I tried on the snippet here and on my website – qadenza Dec 16 '21 at 00:56
  • 1
    remove the width statement; somehow i doubt you really want a 99px wide body. and most likely that's giving you the impression things arent centered. But yes the content should already be centered with just this css code. (though it is quite an outdated way of doing things; a better way being flexbox or grid) – Raxi Dec 16 '21 at 03:58
  • no website needs a 99px body. That's weird. Please post your HTML structure as well. – Raptor Dec 16 '21 at 06:17
  • 1
    @Raptor - actually I need 960px - but on snippet preview here it cannot be recognized because the total space available is less than 960px – qadenza Dec 16 '21 at 10:37
  • add `html {background:#fff}` – Temani Afif Dec 16 '21 at 20:49
  • @qadenza use JSFiddle then – Raptor Dec 17 '21 at 01:57

2 Answers2

0

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 class="content">
  <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>

0

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>
Ali Klein
  • 1,811
  • 13
  • 13