【问题标题】:Image height to stay responsive with no scroll图像高度保持响应没有滚动
【发布时间】:2014-03-01 03:16:47
【问题描述】:

这里是一个简单的问题,但正在努力寻找实现我想要的最佳方式......我有一个图像,我试图在浏览器中保持居中并做出响应。将宽度设置为 100%,图像响应完美(水平)。我遇到的问题是高度。我不希望浏览器滚动并让图像以正确的比例居中,并带有 20 像素的填充。

Dropbox 查看器有一个很好的例子来说明我想要完成的工作,请参见此处:https://www.dropbox.com/s/7zmau5ckx9qe2q1/P-20131215-00017_HiRes%20JPEG%2024bit%20RGB.jpg

使用更多最新代码更新以下内容

我有一个到目前为止的演示(如果你垂直浏览浏览器,滚动条会出现):http://jsfiddle.net/k7JG5/7/

HTML

<div id="top_nav">Logo Here</div>
<div id="img_wrap">
<center><img src="http://goldenleafdesigns.com/images/random-  images/soul_id_select_image1.jpg" /><center>
</div>

CSS

body {
margin: 0px;
padding: 0px;
background-color: #000;
}
#top_nav {
height: 44px;
width: 100%;
background-color: #FFF;
    text-align: center;
    line-height: 44px;
}
#img_wrap {
max-width: 100%;
max-height: 100%;
padding: 20px;
margin-top: 0px;
margin-right: auto;
margin-bottom: 0px;
margin-left: auto;
}
img {
outline: 0;
max-width: 100%;
    max-height: auto;
}

那么,在没有滚动的情况下实现高度以保持响应的最佳方法是什么?

【问题讨论】:

  • 你会用javascript吗?
  • 我对任何事情都持开放态度。 :)
  • 检查我更新的答案,没有js

标签: html css responsive-design width


【解决方案1】:

也许这对你有用:

http://jsfiddle.net/4LNND/

#img_wrap {
    max-width: 100%;
    max-height: 100%;
    padding: 20px;
    margin-top: 0px;
    margin-right: auto;
    margin-bottom: 0px;
    margin-left: auto;
    position:absolute;
    bottom:0;
    left:0;
    right:0;
    top:44px;
}
#img_wrap img {
    outline: 0;
    max-width: 100%;
    max-height: 100%;
    display:block;
}

【讨论】:

  • 这一直有效,直到您将浏览器压缩得更小,然后出现水平滚动。我将最大宽度更改为 90%,这似乎解决了它。效果很好,但是当我尝试在图像上方添加一个 div 时,我遇到了一个更大的问题......我会在上面更新我想要完成的更多细节
【解决方案2】:

有一些比较复杂的方法,这个是最简单的

jsBin demo

HTML:

<div id="img_wrap"></div>

CSS:

#img_wrap{
  position:absolute;
  top:    20px;
  right:  20px;
  bottom: 20px;
  left:   20px;
  background: url('pathToImage.jpg') no-repeat center center fixed;
  background-size: contain;
}

// 如果您不介意图像被截断,请使用cover 代替contain

【讨论】:

  • 这样更接近,但是当浏览器与图像的比例不同时,设置为封面的图像会切断图像。我根本不希望比例或图像被切断。你怎么看?
  • @Greg 编辑了我的答案(仅background-size 属性)和现场示例
  • 太棒了。这完美无缺。我更新了上面的代码以包含标题 div。你觉得如何处理?我将标题添加到您在上面提供的链接中,但 div 最终位于图像后面?
  • 我想通了。我只是将顶部填充更改为 64 像素,以包括顶部导航的高度(即 44 像素)。效果很好!
  • @Greg 太棒了!请记住,background-size 是 CSS3 属性,可能不适用于旧浏览器 (IE)
猜你喜欢
  • 2021-04-27
  • 2018-11-22
  • 2016-01-09
  • 2014-03-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
相关资源
最近更新 更多