Sign Up Login Videos

Centring an HTML element vertically and horizontally

1

Centring an HTML element vertically and horizontally

How would I go about centring an HTML element vertically or horizontally?

  • HTML
  • CSS

3 Replies

This doesn't seem like an appropriate explanation?

I would suggest using Flexbox.

Wrap the item you'd like to center inside of a div. Inside of your stylesheet, apply styles to the div:

display: flex;

If you'd like to center vertically:

align-items: center;

If you'd like to center horizontally:

justify-content: center;

1

This doesn't seem like an appropriate explanation?

I would suggest using Flexbox.

Wrap the item you'd like to center inside of a div. Inside of your stylesheet, apply styles to the div:

display: flex;

If you'd like to center vertically:

align-items: center;

If you'd like to center horizontally:

justify-content: center;

@rgjchandler had a good answer by suggesting you use Flexbox. You can also do it using regular old CSS margins and position properties, so here's an alternative solution.

.mydiv {
    width: 400px;
    height: 400px;

    position:absolute; /*position: fixed would work too*/
    left: 0px;
    right: 0px;
    top: 0px;
    bottom: 0px;
    margin: auto;

    max-width: 100%;
    max-height: 100%;
    overflow: auto;
}

Flexbox is well supported now, so I would recommend that unless you have some reason not to.

≪ Show more ≫
1

@rgjchandler had a good answer by suggesting you use Flexbox. You can also do it using regular old CSS margins and position properties, so here's an alternative solution.

.mydiv {
    width: 400px;
    height: 400px;

    position:absolute; /*position: fixed would work too*/
    left: 0px;
    right: 0px;
    top: 0px;
    bottom: 0px;
    margin: auto;

    max-width: 100%;
    max-height: 100%;
    overflow: auto;
}

Flexbox is well supported now, so I would recommend that unless you have some reason not to.

≪ Show more ≫
x