简体   繁体   中英

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.

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

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM