Reputation: 78676
I followed some guides to make a div to center both vertically and horizontally, but it doesn't work.
<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
Reputation: 1579
if your width and height are 50%, why don't you use
left:25%;
top: 25%;
Upvotes: 0
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
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
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.
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