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

CSS

Centering an image used as an anker (hyperlink)

Hey there, I'm having a little trouble with this.

For the mobile approach, I want to have a logo on top of my nav links which just redirect's the user to home of the site, and I want it to be centered (for now).

Right now, html looks like this:

<a href="http://gazu.carina.uberspace.de" class="main-logo group">
  <img src="img/Gazudin_Logo.png">
</a>

and css:

.main-logo {
    display: block;
    text-align: center;
    margin: auto;
}

It kinda works now, but the area left and right to the image is also clickable, because the link takes up all the space from left to right,with the image in the center. It isn't that bad but it's not what I intended, and I'd like to know how to resolve this, so that just the image is clickable and not all of the space. I tried using inline-block instead of block, which makes only the image clickable, but I haven't been able to center that, it just sticks to the left side then.

Any advice? I know I'm most likely missing something very obvious.

1 Answer

Hey Marcel,

If you put that image into a containing block level element, such as a div, the anchor link's clickable area will only be the size of the image. And then you only have to use "text-align: center" to center the image on the page.

Here's a sample codepen: http://codepen.io/anon/pen/jPyYEY

Hey Marcus, thanks for the quick answer. Yes that does indeed work!

I also found a second solution just now while researching, which is giving the anchor element a width that is the same width as my logo.

Now I have to decide which I like better, having an additional div, or having to manually adjust the anchor width to the width of my image.

The benefit of having just an additional element is that you don't have to make changes to the image's width (or height) to set the clickable area of the logo. This comes into play especially when you want to make the image responsive.

Yeah, I guess that's the better solution after all.