我想显示具有一定宽度和高度的URL中的图像,即使它具有不同的大小比例.所以我想调整大小(保持比例),然后将图像剪切到我想要的大小.
我可以用html img属性调整大小,我可以用background-image.
我怎么能两个都做?
例:
这个图片:

有大小800x600像素,我想像200x100像素的图像一样显示
随着img我可以调整图像200x150px:
<img
style="width: 200px; height: 150px;"
src="http://i.stack.imgur.com/wPh0S.jpg">
Run Code Online (Sandbox Code Playgroud)
这给了我这个:
<img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg">
Run Code Online (Sandbox Code Playgroud)
并且background-image我可以剪切图像200x100像素.
<div
style="background-image:
url('https://i.stack.imgur.com/wPh0S.jpg');
width:200px;
height:100px;
background-position:center;"> </div>
Run Code Online (Sandbox Code Playgroud)
给我:
<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div>
Run Code Online (Sandbox Code Playgroud)
我怎么能两个都做?
调整图像大小,然后将其剪切为我想要的大小?
如果你看一下CSS盒子模型规范,你会看到以下内容:
[margin]百分比是根据生成的框的包含块的宽度计算的.请注意,对于"margin-top"和"margin-bottom"也是如此.如果包含块的宽度取决于此元素,则在CSS 2.1中未定义结果布局. (强调我的)
这确实是事实.但为什么呢?究竟是什么迫使任何人以这种方式设计它?你可以很容易地想到你想要的场景,比如某个东西总是从页面顶部降低25%,但是很难想出为什么你想要垂直填充相对于水平大小的父母.
这是我所指的现象的一个例子:
<div style="border: 1px solid red; margin: 0; padding: 0; width: 200px; height: 800px;">
This div is 200x800.
<div style="border: 1px solid blue; margin: 10% 0 0 10%;">
This div has top-margin of 10% and left-margin of 10% with respect to its parent.
</div>
</div>
Run Code Online (Sandbox Code Playgroud)