Image within anchor tag makes unwanted horizontal space also clickable link

心不动则不痛 提交于 2020-06-01 05:01:18

问题


I am trying to center-align an image in a page while also turning the image into a clickable link. Here is my attempt:

a {
  background: lightblue;
  border: thin solid blue;
}

img {
  background: lightgreen;
  border: thin solid green;
  display: block;
  width: 25%;
  margin: 0 auto;
}
<a href="https://www.example.com"><img src="http://placekitten.com/500/500" alt="kitten"></a>

While the image has become a link, the problem is that most of the horizontal space on both sides of the image has also become clickable link. Why does it happen? Is there anyway to prevent that, so that only the image is a clickable link?


回答1:


I can only think of using a div to centre the image link.

a {
  background: lightblue;
  border: thin solid blue;
}

img {
  background: lightgreen;
  border: thin solid green;
  width: 25%;     
}

.center {
  margin: 0 auto;
  text-align: center;
}
<div class="center">
    <a href="https://www.example.com"><img src="http://placekitten.com/500/500" alt="kitten"></a>
</div>



回答2:


How suggest #yinsweet use container, i use other method with just text align on container like that:

a {
  background: lightblue;
  border: thin solid blue;
}

img {
  background: lightgreen;
  border: thin solid green;
  display: inline-block;
  width: 25%;
  margin: 0 auto;
}
.container{
  
  text-align:center;
  
}
<div class="container">
<a href="https://www.example.com"><img src="http://placekitten.com/500/500" alt="kitten"></a>
</div>


来源:https://stackoverflow.com/questions/61614032/image-within-anchor-tag-makes-unwanted-horizontal-space-also-clickable-link

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!