5

I have the following Html code

<div id="team">
    <h1>Team</h1>
    <img src="assets/divider.png" id="divider">
    <img src="assets/team.png" id="team_pic">
</div>

The following CSS

div#team {
    margin: 0 auto;
    margin-left:auto;
    margin-right:auto;
    right:auto;
    left:auto;
}

However, the child elements divider and team pic are all the way to the left. I though margin:auto would center everything.

then I put the following into the child elements.

div#team img#team_pic {
    width:704px;
    height:462px;
    margin-left:auto;
    margin-left:auto;
}

Nope, nothing happen, the elements still to left and not centered.

8 Answers 8

17

You need to set a width to #team, for example:

div#team {
   margin: 0 auto;
   width: 800px;
}

... which is a shorthand version of:

div#team {
    margin-top: 0;
    margin-left: auto;
    margin-bottom: 0;
    margin-right: auto;
    width: 800px;
}
4

Images are inline level elements by default. You need to use display:block; if you want your images and margin to work properly.

img{
 display: block;
}
2

float will upset this too.. float:none; does the trick if you think it may be inheriting a 'float' directive from another rule somewhere.

2

Team needs to have a width to be able to use margin: auto.

div#team {
    margin: 0 auto;
    width: 400px;
}

Here is a fiddle: JS Fiddle

0

*Use the display:block; for the images classes.*

0
#team { 
    margin: auto; 
    width: 400px;
}

Basically margin depends on width if and only if we want to show our div in the center of the page.

0

If you donot want to give fixed width then we can go for width: max-content;

#team {
  width: max-content;
  margin: 0 auto;
}

0

Another thing that can trip you up is if you have any neighboring display: flex tags.

Sometimes only one sibling will have flex-grow:1 set and it will eat up all the width so margins have no room to auto grow.

To fix this make sure both siblings grow at the same rate. They should have the same flex-grow if you want to center both with margins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.