[Solved] HTML center content through margin auto not working

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.

Solution #1:

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;
}
Respondent: Sandro

Solution #2:

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;
}
Respondent: Gabriel Ferraz

Solution #3:

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

Respondent: Justin Mann

Solution #4:

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

Respondent: btevfik

Solution #5:

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

Respondent: Thilanka De Silva

Solution #6:

#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.

Respondent: Hassaan

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.