0

How can I shrink an anchor (green border) around a centered image of arbitrary (not specified) width? In other words, I want the seconds box with the green border centered, just like the first one. No floats, no absolute positioning.

  • Removing line (A) centers, but the anchor box remains elsewhere and cluttered.
  • Changing line (A) to block makes the anchor full-width
  • No luck with adding margin: 0 auto to the anchor either.

— No chance beyond a (slightly dodgy) text-align center?

enter image description here

Codepen

html

<img src="" width="123" height="100">  
<hr>
<a href='#'>  
    <img src="" width="123" height="100">  
</a>

css

img {
  display: block;
  background: #caa; /* red */
  margin: 0 auto;
}

a {    
  display: inline-block;  /* (A) */
  border: 4px solid #aca; /* green */
}
Community
  • 1
  • 1
Frank N
  • 9,625
  • 4
  • 80
  • 110
  • 3
    There is nothing “dogdy” about using `text-align` to align inline(-block) elements. – CBroe Feb 17 '16 at 14:37
  • Agree with the above. `text-align` is best if you want to keep the width of your anchor dependent on the content. Otherwise you can set the width of your anchor explicitly and use `display:block` – Jordan Burnett Feb 17 '16 at 14:38

2 Answers2

1

If you are set against using absolute position, floats, specific width on the element, AND text-align: center (which is NOT dodgy in the least!), then your only other option is to fake a table.

img {
  display: block;
  background: #caa; /* red */
  margin: 0 auto;
}

a {    
  border: 4px solid #aca; /* green */
  display: table;
  margin: 0 auto;
}

I still don't understand why text-align: center is dodgy...

Daniel C
  • 2,105
  • 12
  • 18
  • **That's a good solution!** ( text-align pushes things from block-resolving to inline-text-flow, whitespace starts to matter, etc... [also see here](http://stackoverflow.com/questions/283961/centering-a-div-block-without-the-width/284064#284064) ) – Frank N Feb 17 '16 at 14:59
0

Wrapping an image in another element merely transfers the centering requirement to the wrapper.

The image will now be centered in the wrapper (the anchor) due to the margin:auto...so you now have to center the wrapper.

BUT you want that wrapper to shrink-to-fit around the image. There are only a few ways on doing that AND centering the result.

Using text-align:center despite the link you mentioned which is seven years old is the optimal and most supported option.

I think you will find that support for text-align isn't even close to spotty any more.

If you want another non-float, non-positioned answer then it will be the less well supported flexbox option.

body {
  display: flex;
  justify-content: center;
}
img {
  display: block;
  background: #caa;
  /* red */
  margin: 0 auto;
}
a {
  border: 4px solid #aca;
  /* green */
}
<a href='#'>
  <img src="http://lorempixel.com/image_output/city-q-c-123-100-3.jpg">
</a>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161