Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering with margin: 0 auto; vs. justify-content and flexbox

Doing some html horizontal center stuff, I just realized that I could use both things to center a box element into its parent, so my question is which of those 2 are better (in terms of performance, usability, etc).

like image 312
DevStarlight Avatar asked Dec 07 '14 14:12

DevStarlight


People also ask

What is the difference between text align center and margin auto?

text-align: center will center the contents of the container, while margin: auto will center the container itself. You should be careful with margin:auto because it is not supported in IE6.

What does margin 0 Auto in CSS do?

So in margin: 0 auto, the top/bottom margin is 0, and the left/right margin is auto, Where auto means that the left and right margin are automatically set by the browser based on the container, to make element centered.

Does margin work with Flexbox?

If you apply auto margins to a flex item, that item will automatically extend its specified margin to occupy the extra space in the flex container, depending on the direction in which the auto-margin is applied.

What happens when margin Auto is applied?

The auto Value You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.


2 Answers

Because of the way margins are handled in flex, these do the same job.

But as a general practice, when you have more div's, using flex would do the job more accurately and will provide you choice for distributing the space equally". When you have few div' , you can go with margin:auto . Remember flexbox provides us the choice for redistributing the space.

like image 63
Aakash Sr Avatar answered Oct 03 '22 04:10

Aakash Sr


If you use div or p it's better to use margin: 0px auto; for containers or main page, But if you need two or more children to be centered, it's better to set parent to text-align:center and the children to display: inline-block.

like image 24
Gega Gagua Avatar answered Oct 03 '22 05:10

Gega Gagua