简体   繁体   中英

How to center an img tag into div tag when I resize the browser?

I am new to web development and I love it, but I've have encountered a problem and I can't figure it out.

I really want my images inside of my div element to be like : http://jsfiddle.net/eb51hxj1/ when i resize the browser.

 <div class="divImage">
    <img id="image"> </div>
 <div>

My code is :

https://jsfiddle.net/a2bsarfb/

Flexbox is your friend!

.divImage {
  display: flex;
  justify-content: center;
  align-items: center;
}

align-items centers the div content along the cross-axis (vertically, in this case), justify-content centers the div content along the main axis (horizontally).

Remove one or the other if you so desire.

You can just set the max-width of the .divImage to be 100%:

.divImage {
    max-width: 100%;
}

Just be careful of sizing, because the height will change to keep the size ratio the same. If you explicitly set the height, the resizing won't happen, but the ratio might look weird as you resize.

Since block-elements always try to take up the full width of their parent you can use that to your advantage.

#image {
    display: block;
    margin: 0 auto;
}

That's also how the Fiddle you linked did it.

You should use var
less code and make more

var divImage = document.getElementById('divImage');
....
divImage.style.backgroundImage = "url("+nextImage+")";
...
divImage.style.opacity = opacity;

remove img tag and put

<div class="divImage" id="divImage"><div>

and css
background-repeat: no-repeat

.divImage {
    max-width: 100%;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    /*background-image: url(...)*/
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM