Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML center content through margin auto not working

Tags:

html

css

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.

like image 493
jason white Avatar asked Nov 29 '22 02:11

jason white


2 Answers

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;
}
like image 145
Sandro Avatar answered Dec 09 '22 20:12

Sandro


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;
}
like image 38
Gabriel Ferraz Avatar answered Dec 09 '22 20:12

Gabriel Ferraz