1

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;
}
Stickers
  • 75,527
  • 23
  • 147
  • 186

4 Answers4

3

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>
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1

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%);
}
atmd
  • 7,430
  • 2
  • 33
  • 64
1

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/

YourFriend
  • 434
  • 4
  • 7
0

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

left:25%;
top: 25%;
P.Petkov
  • 1,569
  • 1
  • 12
  • 20