简体   繁体   English

调整浏览器大小时,如何将img标签置入div标签中?

[英]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. 我是Web开发的新手,但我很喜欢它,但是遇到了一个问题,无法解决。

I really want my images inside of my div element to be like : http://jsfiddle.net/eb51hxj1/ when i resize the browser. 当我调整浏览器大小时,我真的希望我的div元素中的图像像: http : //jsfiddle.net/eb51hxj1/

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

My code is : 我的代码是:

https://jsfiddle.net/a2bsarfb/ https://jsfiddle.net/a2bsarfb/

Flexbox is your friend! Flexbox是您的朋友!

.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). align-items使div内容沿横轴居中(在这种情况下,垂直),justify-content使div内容沿主轴居中(水平)。

Remove one or the other if you so desire. 如果需要,请删除其中一个。

You can just set the max-width of the .divImage to be 100%: 您可以将.divImage的最大宽度设置为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 您应该使用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 删除img标签并放入

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

and css 和CSS
background-repeat: no-repeat

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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