Reputation: 3765
I'm trying to align a button in the middle of a scalable/responsive div. The problem is, the button isn't actually centered here. What am I missing? fiddle
div{
text-align: center;
}
button{
position: absolute;
top: 50%;
left: 40%;
}
Upvotes: 1
Views: 165
Reputation: 1352
Here is your updated fiddle http://jsfiddle.net/pMxty/122/
a Bit of jQuery resolves it.
HTML
<div>
<button>Load my random useless data</button>
</div>
css
div {
text-align: center;
}
button {
position: absolute;
top: 50%;
}
jQuery
function place()
{
var a = $("div").outerWidth() / 2,
b = $("button").outerWidth() / 2;
$("button").css({
"left": (a - b)
});
}
$(document).ready(function(){
place();
$(window).resize(function(){
place();
});
});
Upvotes: 0
Reputation: 157314
When you use position: absolute;
for centering elements, you need to negate the margin
which are half of the size of the absolute
positioned element. So say if your button
is 100px
in width
you need to negate margin-left: -50px;
So in your case, am hardcoding 250px
of the width
so I negated -125px
, same goes for height
as well, if the height
of the element is say 30px
use margin-top: -15px;
button{
position: absolute;
top: 50%;
left: 50%;
margin-left: -125px;
width: 250px;
/* Use height as well if you need so, along with margin-top which
will have 1/2 of the negative value of the elements height */
}
The other way to achieve this is to use display: table-cell;
with vertical-align
set to middle
On the other hand, if you do not want to use negative margin
you can use calc()
as well
button{
position: absolute;
top: 50%; /* Use calc here too if you define height */
left: calc(50% - 125px); /* Half of the elements width */
width: 250px;
}
Upvotes: 2