CSS无法强制图像宽度和高度

时间:2016-02-16 20:25:55

标签: html css

我正在尝试显示具有特定大小和隐藏溢出的全景图像,以最终实现用户引发的平移(下面不包含代码)。

我正在以这种方式添加图片:

<div class="pan">
<img src="http://lorempixel.com/image_output/sports-q-c-1920-480-7.jpg">
</div>

我正在以这种方式设置图像尺寸参数:

.pan {
  width: 800px;
  height: 400px;
  overflow: hidden;
  border: red solid;
}

但是,当我改变宽度时,高度会按比例变化,而且我没有任何溢出来隐藏。图像为13632×2936。

这是我从上面的代码得到的结果:

enter image description here

以这种方式设置尺寸时,我会得到以下图像:

.pan {
  width: 400px;
  height: 400px;
  overflow: hidden;
  border: red solid;
}

enter image description here

尝试覆盖设置为100%的img参数(出于其他目的),我得到一个扭曲的图像 - 仍然没有隐藏的溢出:

.pan img {
  height: 800px;
  width: 400px;
  transition: opacity .6s linear .8s;
}

enter image description here

与.pan和容器相关的其他代码(来自下面引用的教程):

.pan img{
  transition: opacity .6s linear .8s;
}

.pan img.loaded{ opacity: 1; }

.img-pan-container, .img-pan-container img{ -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; }

.img-pan-container{
  position: relative;
  overflow: hidden;
  cursor: crosshair;
  height: 100%;
  width: 100%;
}

.img-pan-container img{
  -webkit-transform: translateZ(0); -ms-transform: translateZ(0); transform: translateZ(0);
  position: absolute;
  top: 0;
  left: 0;
}

对于信息,我正在尝试实现此example。但是,我目前没有将我的问题集中在其余的平移代码上,因为我遇到的问题只是通过隐藏的溢出来正确地调整图像大小。

2 个答案:

答案 0 :(得分:4)

img儿童必须大于父.pan,请参阅下面的代码段,其中包含1920px width和480px height的图片。但这会裁剪部分图像。

.pan {
  width: 800px;
  height: 400px;
  overflow: hidden;
  border: red solid /* demo */
}
img {
  display:block /* fix inline gap */
}
<div class="pan">
  <img src="http://lorempixel.com/1920/480/" />
</div>

<强>更新

根据您更新的问题,您的css img很可能设置为max-width:100%,请在上面看到与该属性集相同的代码段。

.pan {
  width: 800px;
  height: 400px;
  overflow: hidden;
  border: red solid /* demo */
}
img {
  display:block; /* fix inline gap */
  max-width:100% /* YOUR ISSUE */  
}
<div class="pan">
  <img src="http://lorempixel.com/1920/480/" />
</div>

更新 OP的评论:

  

情况可能就是这样......我如何只为这个班级覆盖img

如果您无法找到原点和/或希望保留其他max-width:100%的{​​{1}},则可以使用img上的max-width:none覆盖

.pan > img
.pan {
  width: 800px;
  height: 400px;
  overflow: hidden;
  border: red solid  /* demo */
}
img {
  display: block;  /* fix inline gap */
  max-width: 100%  /* YOUR ISSUE */
}
.pan > img {
  max-width: none
}

答案 1 :(得分:1)

您可以尝试使用此css存档图像的封面效果:

.pan {
    ...
    position: relative;
}
img {
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    transform: translate(-50%, -50%);
}

JSFiddle here

相关问题