Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center elements in a web page - margin 0 auto or left 50%?

Tags:

html

css

In order to center elements inside a parent container using CSS, I always did this:

div.element-to-center { width: ...; margin: 0 auto; }

but I've always had the feeling that this is not the right way to do it; I'm not too much confident with margins in general.

I know you could go with position: fixed; and left:50%; top:50%; and then do your calculations with margins in order to position the element in the exact center... But is it a valuable choice?

My question is: is margin: 0 auto; a good technique to center elements on a page? Can I do better in other ways?

like image 393
whatyouhide Avatar asked Dec 07 '25 01:12

whatyouhide


1 Answers

Yes, margin: 0 auto; is a good technique.

Left: 50% needs a non-static position, and it does not center, because it starts your div from 50% of the total width, without considering the lenght of the div itself.

To use Left correctly you should (know and) subtract half of the width of your div to the value, with CSS3 Calc:

Demo: http://jsfiddle.net/r7EwW/

HTML

<div class="auto">Div with margin: 0 auto;</div>
<div class="percentage">Div with Left: 50%;</div>
<div class="percentageDynamic">Div with Left: (50% - half of div's width) </div>

CSS

div.auto {
    width: 100px;
    border: 1px solid green;
    margin: 0 auto;    
}

div.percentage {
    width: 100px;
    border: 1px solid red;
    position: relative;
    left: 50%;    
}


div.percentageDynamic {
    width: 100px;
    border: 1px solid green;
    position: relative;
    left: calc(50% - 50px);    
}
like image 140
Andrea Ligios Avatar answered Dec 08 '25 15:12

Andrea Ligios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!