Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTushar Arora
1,760 PointsMargin: 0 auto ; Does not center the image on page.
I want to center one and only image in the body on this page. I tried using margin: 0 auto; but it did not worked. Why is it so ?
This is my simple html code.
<! DOCTYPE html>
<html>
<head>
<title>Tushar Arora | Software Developer</title>
<meta charset="utf-8"/>
<link href="css/normalize.css" rel="stylesheet"/>
<link href="css/main.css" rel="stylesheet"/>
</head>
<body>
<img src="img/earth.gif" id="earth"/>
</body>
</html>
This is simple Css code
#earth {
margin: 0 auto;
}
2 Answers
Inge L
30,058 PointsThere is one great article about centering elements: https://css-tricks.com/centering-css-complete-guide/
<! DOCTYPE html>
<html>
<head>
<title>Tushar Arora | Software Developer</title>
<meta charset="utf-8"/>
<link href="css/main.css" rel="stylesheet"/>
</head>
<body>
<div id="earth">
<!-- <div class="earth"> -->
<img src="img/earth.gif" alt="" >
<!-- </div> -->
</div>
</body>
</html>
/* inline - center horizontally
#earth {
text-align: center;
}
*/
/* block - center horizontally */
#earth {
margin: 0 auto;
/* width of the image */
width: 297px;
}
/* block - center horizontally and vertically
.earth {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
*/
Inge L
30,058 PointsUse width and put how much pixels image is wide.
"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: " - http://www.w3schools.com/css/css_margin.asp
Jonathan Selwall
12,528 PointsHey! It's because images are Inline-blocks, if you do this it should work:
img{
margin: 0 auto;
display: block;
}
If you want to align inline elements you can just put text-align: center on the container.
Tushar Arora
1,760 PointsTushar Arora
1,760 PointsThanks for the good article but even if I use the below code then also the image will not come to center
I dont know why in tutorials it has been told many times that if you want to center an element use margin : 0 auto;