Absolute positioning with negative top/left/right/bottom for image stretching

荒凉一梦 提交于 2020-01-04 07:27:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40317120/absolute-positioning-with-negative-top-left-right-bottom-for-image-stretching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!