Center anchor with image in div

2019-03-22 06:53发布

I have an image that's in an anchor element.

I want the anchor an the image to be centered both vertically and horizontally in the parent div.

Here's an example:

<div class="wrapper">
    <a href="#" class="anchor">
        <img src="http://bit.ly/1mFH8AW"></img>
    </a>
</div>
.wrapper {
    background: black;
    width: 500px;
    height: 500px;
}
.anchor {
}
.anchor > img {
    height: 100px;
    width: 100px;
}

Result:

enter image description here

1条回答
Melony?
2楼-- · 2019-03-22 07:16

Add position:relative to your wrapper and then change the image's CSS to:

.anchor > img {
    height: 100px;
    width: 100px;
    position:absolute;
    margin:auto;
    top:0;right:0;bottom:0;left:0;
}

jsFiddle example

查看更多
登录 后发表回答