Marilee Marilee - 1 month ago 6
CSS Question

CSS/HTML Centre Box

Im looking at this beautiful piece of webdesign, notice how the box is perfectly centered in the middle of the screen, I have looked through the source code of the page but it does not make much sense to me.

(Web site Link to view full example, click here)

All I can really make out is that they are using, the below code at the top of their stylesheet.

*, *:before, *:after {
box-sizing: border-box;
}


In short I would like to know what would be the easiest and most efficient way to center a box like on the image on the center of the screen.

enter image description here

Answer

Apply the box you want to center a margin: 0 auto;.

Though you will also need to make sure the item can be centered. For this, correct its width to be less than the full width of the HTML <body>.

enter image description here

As you can see in this image, the real magic is being done by the following code:

#preview-container-id {
  margin: 0 auto;
  width: 70%;
}

With this, they executed the two steps mentioned in my answer.

If you de-activate those two properties you'll notice that the box goes all the way to the left.

And just as Luke Robertson mentioned, there are different ways to approach this. My solution is for a block-level item, but if you had an inline-level item this solution would not work at all.

Answer for comment Q's:

The box-sizing: border-box sums up all the cumulative width and height set by margins and padding with the size defined for the elements.

Notice the size of the highlighted element without left padding and with border-box active: Item with left padding de-activated and border-box active

Now, check the width with the left padding active:

Item with left padding and border-box active

Do you see any change?

Now, lets de-activate border-box and leave the padding on:

Item with left padding de-activated and border-box de-activated

Now this looks ugly, and it's exactly what border-box prevents

As you can see on a quote from this CSS-Tricks post:

This is often called "universal box-sizing", and it's a good way to work! The (literal) width you set is the width you get, without having to perform mental math and manage the complexity that comes from widths that come from multiple properties.

And no, you don't need to set any extra CSS on the <body> or <html> tags, as they already come with the required properties to allow you center block-level items :)

Comments