开发者

Completely center an image?

开发者 https://www.devze.com 2022-12-09 12:21 出处:网络
I have a div and an image within the div. The image size will vary. I want it to be centered ho开发者_如何转开发rizontally and vertically. Css verticle align does\'t seem to work.

I have a div and an image within the div. The image size will vary.

I want it to be centered ho开发者_如何转开发rizontally and vertically. Css verticle align does't seem to work.

Any tricks? I can use php, css or Jquery


You can get it to align horizontally by using

margin: 0 auto;

Centring vertically isn't easy with CSS (at least not in IE6/7). It's relatively easy to do it with tables.

You say you have jQuery available. You can kick any browser into gear by applying JavaScript. But of course without JS enabled/supported, your page will not appear correctly.

CSS's vertical-align property is only meant to be used within something with display: table-cell (which itself should be in something with display: table).

If you had

<div id="container"><img src="my-image.png" alt="" /></div>

You could use jQuery to center it like this (as in the suggestion by plexus)

var imageSrc = $('#container img').attr('src');

$('#container').css({ backgroundImage: 'url(' + imageSrc + ')', backgroundPosition: 'center enter' });


I don't know how you use it, so probably my solution won't fit.

When you implement the image as a 'background-image' within the div you can easily center it with 'background-position':

#div {
background-image: url(./image.png);
background-position: center center;
}


<style>
    .image-container {
        position:relative;
        width:300px;
        height:300px;
        background:#ccc;
    }
    .image-container .image {
        position:absolute;
        top:50%;
        left:50%;
        transform:translate(-50%, -50%);
        background:red;
        height:100px;
        width:100px;
    }
</style>
<div class="image-container">
    <img class="image" src="****.jpg"/>
</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号