Last Updated: February 18, 2020
·
2.118K
· jonlunsford

CSS, center elements with varying width and height

Example markup where the width or height can change or is unknown:

<main>
    <div class="item-centered">
      <p>This content length may change based on user input.</p>
    </div>
</main>

Using CSS3 transforms and the translate property:

main {
   position: relative;
}

// Vertically centered only
.item-centered {
    position: absolute; // can also be relative
    top: 50%;
    transform: translateY(-50%); // left out prefixes for brevity
}

// Horizontally centered only
.item-centered {
    position: absolute;
    left 50%;
    transform: translateX(-50%);
}

// Horizontally and vertically centered
.item-centered {
    position: absolute;
    left 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

Example:

Codepen

4 Responses
Add your response

I always have to look up how to do this stuff, now I can just come look at this. Thanks.

over 1 year ago ·

Thanks! I'm glad it can be of use.

over 1 year ago ·

Does it work on < IE9?

over 1 year ago ·

Unfortunately this exact solution will not work in < IE9, however you could implement a JS solution for earlier versions of IE.

If you know the width of your element you could use the "negative margins" technique:

.my-element {
    position: absolute;
    width: 200px;
    height: 200px;
    left: 50%;
    top: 50%;
    margin: -100px 0 0 -100px
}
over 1 year ago ·