问题
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