How do you align vertically in CSS3 & HTML5?

I want all the contents of the tag to align vertically inside the tag, without specifying a height for body, but the HTML being of height 100% (for the purposes of a background gradient).

  • Just to be clear, it's the green part you're trying to centre vertically? Kev almost 7 years ago
  • I want to align so that the body tag (in white with 3 rounded corners) appears in the center of the html tag both horizontally and vertically (the grey background) digiguru almost 7 years ago

1 answer

o.k.w 2355
1
point

Is there any issue with specifying the body height as 100%? Is not, here's one way you might want to try.

Using another container to wrap around the element you want to vertical aligned in the entire body.

CSS (Note the comments within the style definition):

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}
#wrapper {
    position: relative;
    height: 100%;
    width: 400px; /* container width to be same as that of the target element*/
    margin: 0 auto; /* horizontal aligned center*/
}
#contentBody {
    position: absolute;
    top: 50%;
    width: 400px; /* width of target element */
    height: 300px; /* height of target element */
    margin-top: -150px; /* Important: HALF the height of target element */
}

HTML:

<body>
<div id="wrapper">
<div id="contentBody" style="background-color: #333333; color: #ffffff;">
<p>This is vertically centered</p>
</div>
</div>
</body>
Answered almost 7 years ago by o.k.w
  • Interesting, but nothing new - surely HTML5 and CSS3 have a better solution? digiguru almost 7 years ago
  • I agree this isn't using any new CSS3 or HTML5 options. That being said, I'm having difficulty figuring out a better way. James VanDyke over 6 years ago