jquery - 将图像放置在浏览器的 100% 宽度和 100% 高度的 div 中

标签 jquery html css height width

你好,这个问题真的很简单,但无法弄清楚。

我想用图像填充浏览器,这样无论用户在浏览器中调整大小,我的图像都会填充内容。

我还需要图像保持居中,这样如果用户缩小浏览器,图像将保持居中并首先失去边缘,希望他说得有道理。

这背后的原因,我打算在它的位置放置一个插件,称为图层 slider 。

这是我的代码

<div id="div1">
<img src="images/gifts.jpg" height"100%" width"100%">
</div>

编辑 1:抱歉忘了补充一点,我需要保持图像的比例,这样如果用户减小浏览器的宽度,图像将保持居中但会开始丢失边缘,如果用户随后减小浏览器的宽度高度,图像将缩小,因此无论浏览器的高度或宽度如何,它始终保持比例。

编辑 2:这是我想要的链接,但我需要将图像放在 div 中。

谢谢

最佳答案

将高度和宽度应用于分隔线本身。

#div1 { height:100%; width:100%; }

如果分隔线的高度不起作用,您需要更改页面的 html 和正文,使其也具有 100% 的高度。清除填充和边距也是一个好主意。

html, body { height:100%; padding:0; margin:0; }

JSFiddle .

如果您还希望该分隔线出现在后面的其他内容之上,您需要将其 z-index 设置为大于后面的内容并定位分隔线:

body { position:relative; z-index:1; }
#div1 { position:fixed; z-index:1000; }

编辑:

为了保持图片的比例:

/* If the browser doesn't support media queries */
div#div1 img { height:100%; width:100%; }

/* If the screen is portrait */
@media screen and (orientation:portrait) { 
    div#div1 img { height:auto; width:100%; }
}

/* If the screen is landscape */
@media screen and (orientation:landscape) {
    div#div1 img { height:100%; width:auto; }
}

已更新 JSFiddle .

关于jquery - 将图像放置在浏览器的 100% 宽度和 100% 高度的 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14895075/

相关文章:

html - CSS:在填充内设置内联元素

javascript - 有没有一种方法可以在不使用触发事件的情况下启动 css transition?

html - 如何使浏览器的黑色跨度宽度?

javascript - ajax GET 函数在被另一个函数调用时不返回成功值

jquery - 同步动画 : how to shrink font size while moving left using jQuery

html - ASP.NET MVC : input-validation-valid applied style not working

javascript - 我应该在前端还是后端处理 html 表单验证?

html - CSS 导航栏链接背景色悬停

javascript - 不允许用户停止 javascript alert()

jquery - 检查此数组中的值,JQuery