英文:
How can I center an image in an anchor element?
问题
在这一刻,div
元素中的图像使用了 flex
和一些 CSS 来排列它们成一个框。与此同时,问题似乎出现在我想要将图像居中于 CSS 框的情况下。
我尝试过使用 text-align: center
和外边距来实现,但这会使锚点元素靠得更近。我想要的是在保持链接之间的距离的同时,将图像居中于框的中央。
我目前看到的是:
如您所见,在最后两个框中,图像对齐到了左上角,而不是中央。
我想要实现的效果(点表示图像):
.image-list {
display: flex;
flex-wrap: wrap;
justify-content: center; /* 将这一行修改为center */
margin-left: auto;
margin-right: auto;
align-items: center;
margin-top: 20px;
padding-left: 80px;
}
.image-list img {
width: 50px;
height: 50px;
margin-right: 10px;
margin-bottom: 10px;
object-fit: contain;
/* justify-content: center; 这一行可以删除 */
}
<div class="image-list">
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
</div>
英文:
In this moment, the image in the div element uses flex, and some CSS to sale them into a box of some sort. Meanwhile the problem seem to be when I want to center the images to the center of the CSS box.
I tried to do it with text-align: center
and also with margins, but that makes the anchor elements closer to one another. What I want is to keep the distance between the a links while the images are centered to to center of the box.
What i see right now:
as you see in the last two boxes the images are aligned to the top left, and not to the center.
What i want to achieve (dots are the image):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.image-list {
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
margin-left: auto;
margin-right: auto;
align-items: center;
margin-top: 20px;
padding-left: 80px;
}
.image-list img {
width: 50px;
height: 50px;
margin-right: 10px;
margin-bottom: 10px;
object-fit: contain;
justify-content: center;
}
<!-- language: lang-html -->
<div class="image-list">
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
<a href=""><img src="https://via.placeholder.com/80" alt=""></a>
</div>
<!-- end snippet -->
答案1
得分: 1
目标选择 .image-list 并设置 display 属性为 flex,以及其他所需的属性,如下所示:
.image-list a {
display: flex;
justify-content: center;
align-items: center;
}
您还需要在 .image-list 上使用 flex-direction: column;。
英文:
target the .image-list and display flex along with other desired attribute like so;
.image-list a {
display:flex;
justify-content: center;
align-items:center;
}
You will also want to use flex-direction:column; on the .image-list
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论