简体   繁体   中英

Why <img>'s are not stretched when sized with left / right / top / bottom vs width / height

I'd like to understand why <img> behaves differently to the rest of block elements when size is defined implicitly (via top/left/bottom/right) instead of (top/left/width/height).

An <IMG> is better than a thousand words, so please take a look at the snapshot below:

图解说明

Also I'd like to know if I can force the behaviour of the explicit size using implicit size via additional CSS.

The CSS

.container {overflow:hidden; position:relative; width:200px; height:200px; display:inline-block; }
#implicitsize { position:absolute; top:0px; left:0px; right:0px; bottom:0px; }
#explicitsize  { position:absolute; top:0px; left:0px; width:100%; height:100%; }

And the HTML

<div class="container"><img id="explicitsize" src="https://c2.staticflickr.com/4/3293/3129420363_ea8515d81a.jpg"></div>
<div class="container"><img id="implicitsize" src="https://c2.staticflickr.com/4/3293/3129420363_ea8515d81a.jpg"></div>

PD- Fiddle at http://jsfiddle.net/uzsbnex8/2/

这是因为您可以使用widthheight来设置图像的尺寸,并使用top,left,bottom,right来设置位置,而不会影响尺寸。

This is because <img> is a replaced element .

For absolutely positioned replaced elements , if the values of top / bottom are over-constrained, once you set a value for top , bottom would be ignored. This is true for left / right properties as well.

10.3 Calculating widths and margins / 10.3.8 Absolutely positioned, replaced elements

  1. If at this point the values are over-constrained, ignore the value for either 'left' (in case the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.

10.6 Calculating heights and margins / 10.6.5 Absolutely positioned, replaced elements

  1. If at this point the values are over-constrained, ignore the value for 'bottom' and solve for that value.

Therefore in this case the absolutely positioned <img> element would be position with the respect to top and left offsets and it will NOT be stretched by top , bottom , right and left properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM