Easy Vertical and Horizontal Centering in HTML
Let’s say you’re designing a website, and you want an image or a block of text centered vertically and horizontally in the viewport (browser window). You can do that in a couple of ways without resorting to a table.
If you want the element to size itself to the viewport, use fixed positioning to place the item on the page. Define the element’s width as a percentage, and then split the remainder between left: and right: properties. After that, define the element’s height as a percentage, and split the remainder between the top: and bottom: properties. Here’s an example:
Of course, the element will take on the size and shape of the browser window because you sized everything in percentages.
If you want to give the centered element a static, non-changing size, use fixed positioning again. But set both the top: and left: positions both to 50%. Define the height in pixels, and then set the top margin to -1 times half that height. After that, define your width in pixels. Then set the left margin to -1 times half that width, like this:
Here’s a page you can experiment with and keep for future reference. In the <div> to which you’re applying the styling, use either id=”centerpct” or id=”centerpx”, the view in a browser.
Try changing the browser window size to see how the element remains centered. (With the pixel-sized element, it’ll be possible to make the browser window smaller than the centered element, in which case it won’t look centered anymore since some parts will be cut off).
If the gray square doesn’t really help you envision the difference, you could use an image instead of the fit <div>, as below, but replace sample.png with a reference to an image of your own.
Happy coding!