Stickers
Stickers

Reputation: 78676

Center div both horizontally and vertically using absolute position

I followed some guides to make a div to center both vertically and horizontally, but it doesn't work.

http://jsfiddle.net/ony80a5d/

<div class="c">center</div>

html, body {
    height: 100%;
}
.c {
    background: grey;
    width: 50%;
    height: 50%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

Upvotes: 1

Views: 64

Answers (4)

P.Petkov
P.Petkov

Reputation: 1579

if your width and height are 50%, why don't you use

left:25%;
top: 25%;

Upvotes: 0

YourFriend
YourFriend

Reputation: 434

You haven't set margins anywhere in your code. Just put this margin:auto in your .c class . For Example http://jsfiddle.net/ony80a5d/4/

Upvotes: 1

atmd
atmd

Reputation: 7490

You've set your element to be of width 50%, but you haven't set any positioning other then zero values for top/left etc. set your top and left to 50% and transform the position, like this:

.c {
    background: grey;
    width: 50%;
    height: 50%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 240878

One option would be to add margin: auto to the element. In modern browsers, this will center the element horizontally/vertically.

For more approaches on centering an element horizontally/vertically, see this answer.

Updated Example

html, body {
    height: 100%;
}
body {
    margin: 0;
}
.c {
    background: grey;
    width: 50%;
    height: 50%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto
}
<div class="c">center</div>

Upvotes: 3

Related Questions