Capuchin
Capuchin

Reputation: 3765

Aligning a button center middle (long text)

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

Answers (4)

Mayank Tripathi
Mayank Tripathi

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

Mr. Alien
Mr. Alien

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  */
}

Demo


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;
}

Demo 2

Upvotes: 2

Bikas
Bikas

Reputation: 2759

You have to reduce the height/ width of the button from it's position as well. Try this

button{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -112px;
    margin-top: -25px;
}

Fiddle DEMO

Upvotes: 0

Manoj
Manoj

Reputation: 1890

Try this code:

DEMO

button{
    position: absolute;
    top: 50%;
    left:25%;
    width:50%
}

Upvotes: 1

Related Questions