问题描述
我刚刚发现了纯CSS解决方案来拉伸像background-size:cover
这样的图像.它由Twitter使用,但以其他形式使用.
以下是拉伸图像的示例(不是我的示例) http://jsfiddle.net/zksd1L6a/1/
在大多数情况下,它都可以正常工作,并且我不需要使用Javascript
将我的图片适合div
这是代码
div {
position: relative;
background: yellow;
overflow: hidden;
}
.parent1 {
width: 500px;
height: 200px;
}
.parent2 {
width: 500px;
height: 300px;
}
img {
position: absolute;
left: -9999px;
right: -9999px;
top: -9999px;
bottom: -9999px;
margin: auto;
min-width: 100%;
min-height: 100%;
}
和html
<h2>Would Work</h2>
<div class="parent1">
<img src="http://placehold.it/300x150" alt="" class="img1" />
</div>
<h2>Also Works</h2>
<div class="parent2">
<img src="http://placehold.it/300x150" alt="" class="img2" />
</div>
我的问题是关于职位空缺-9999px
有人可以解释它是如何工作的,为什么它会以这种方式运行,如果有人从浏览器的角度解释它是如何工作的,那将是很好的.
正如我可以猜测的那样,将块顶部放到-9999px,而不是放到-9999px,这将导致绝对高度为19998(-9999px +(-9999px)).为什么图像不能以这种方式拉伸.
请解释一下.
基本上,您的意思就是正在发生的事情.
图像的高度和宽度确实为19998px
,但是与其设置内容大小,不如为您设置margin
.用户代理可以随意猜测其可能的位置.在 w3规范
由于边距相等,因此图像会自动在假设框中居中
.I have just found pure CSS soltution for stretching image like background-size:cover
.It is used by Twitter but in a little bit other form.
Here is an example (not mine) for stretching image http://jsfiddle.net/zksd1L6a/1/
In most cases it works just fine and I have no need to use Javascript
to fit my image into div
Here is code
div {
position: relative;
background: yellow;
overflow: hidden;
}
.parent1 {
width: 500px;
height: 200px;
}
.parent2 {
width: 500px;
height: 300px;
}
img {
position: absolute;
left: -9999px;
right: -9999px;
top: -9999px;
bottom: -9999px;
margin: auto;
min-width: 100%;
min-height: 100%;
}
And html
<h2>Would Work</h2>
<div class="parent1">
<img src="http://placehold.it/300x150" alt="" class="img1" />
</div>
<h2>Also Works</h2>
<div class="parent2">
<img src="http://placehold.it/300x150" alt="" class="img2" />
</div>
My question is about negative positions -9999px
Could someone explain how this work and why it behaves in this way, it would be great if someone explains from browser perspective how it works.
As I can guess it doing something like that put block top to -9999px and than put it down to -9999px this results in absolute 19998 height (-9999px + (-9999px)). Why than image is not stretched this way.
Please explain this.
Basically, what you are saying is exactly what is happening.
The image is indeed 19998px
in height and width, but rather than setting the content size it will set margin
for you instead. User agents are free to make a guess at its probable position. It is explained in The w3 specification
Because the margins are equal, the image is automatically centered in the hypothetical box.
这篇关于负上/左/右/下负值的绝对定位,用于图像拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!