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 trial
Alita Edmonds
6,068 PointsPositioning an image Centering the image in the browser.
What property and value could I use to make an image position in the center of the webpage, no matter the width of the browser. Thanks!
7 Answers
Steven Parker
243,318 PointsFor "margin: auto;" to work on an "img" element, you need to convert it to display in "block" mode:
img {
display: block; /* block mode to allow centering */
max-width: 500px;
width: 50%;
margin: auto;
}
p {
text-align: center; /* the other method will work well on the paragraph */
}
Matt Brock
28,330 PointsThe best way to center elements on the x-axis is to set their left and right margins to auto. This only works on block elements, so you'll have to set that if the element's default style is not block. I made a quick Pen for you for reference: https://codepen.io/mattpbrock/pen/rYOJBp.
If you're trying to center vertically, that's a bit trickier, but still possible in most situations. Does that help?
Steven Parker
243,318 PointsThere are a few different techniques for this, and it depends on the element itself and what other element it is contained in.
If it's a text element, you might only need:
text-align: center;
If it's something with block mode and an explicitly constrained width:
margin: auto;
Otherwise, you could should show your actual code for a more specific answer.
Alita Edmonds
6,068 PointsThank you. The margin: auto didn't work, but I think I am missing something. Here is my code. My image is inside a <a> tag, in the <body> element. Hope this helps. Thanks!
<a href="img/computer.jpg">
<img src="img/computer.jpg" alt="">
<p>Photo of me.</p>
</a>
Alita Edmonds
6,068 PointsThis is my CSS for it.
img { max-width: 500px; margin: 10px 550px; width: 50%; margin: auto; }
Matt Brock
28,330 PointsThe <a> tag must be set to display: block for this to work. If you need the entire image link horizontally centered, try this:
a {
display: block;
}
img {
max-width: 500px;
width: 50%;
margin: 10px auto; /* important bit */
}
Alita Edmonds
6,068 PointsThank you Matt for explaining it. It really helped me understand. I really appreciate it.
Alita Edmonds
6,068 PointsThanks Steven. Your method worked! I appreciate it.