屏幕缩小时背景图裁剪高度

huangapple go评论69阅读模式
英文:

background image crop height when the screen is reduced

问题

我有一个带有背景图片的 div

<div class="blog-img" style="background-image: url('{{ $blog->imgUrl }}');"></div>

问题是,我无法在不设置固定高度和宽度的情况下渲染这张图片

CSS:

.blog-img {
  width: 600px;
  height: 500px;
  background-size: 100% auto; 
  background-position: unset;
  background-repeat: no-repeat;
}

所有的输出几乎都是我需要的,但唯一的问题是高度的部分。当我减小屏幕尺寸时,我需要切掉块的额外部分,但由于设置了固定高度,这并没有发生。

屏幕缩小时背景图裁剪高度

我该如何使得在屏幕缩小时,所选的这部分被切掉?

英文:

I have a div with a background image

&lt;div class=&quot;blog-img&quot; style=&quot;background-image: url(&#39;{{ $blog-&gt;imgUrl }}&#39;);&quot;&gt;&lt;/div&gt;

The problem is that I can't render this image without setting the styles to a fixed height and width

CSS:

.blog-img {
  width: 600px;
  height: 500px;
  background-size: 100% auto; 
  background-position: unset;
  background-repeat: no-repeat;
}

Everything outputs almost the way I need, but the only thing is the problem with the height. When I reduce the screen, I need to cut off the extra piece of the block, but this does not happen due to the fact that a fixed height is set

屏幕缩小时背景图裁剪高度

How can I make it so that when the screen is reduced, this piece that I selected on the screen is cut off?

答案1

得分: 1

你有两个选择,据我所见:

  1. 在与图片相匹配的 div 上设置 aspect-ratio,以确保 div 的任何宽度都具有与图片相匹配的高度,从而不会被拉伸或裁剪。确保使用 background-size:contain
  2. background-size 设置为 cover,这样图像将自动裁剪,但适合 div 的所有尺寸。提示:您可以调整 background-position 属性,以确保图片中您最关心的部分可见,例如 center center

如果您只关心图片正确显示,请选择第二个选项。但是,如果 div 内有内容或者 div 的大小不受您控制,请选择第一个选项。

英文:

You have two options as far as I see it:

  1. Set aspect-ratio on the div that matches the aspect ratio of your picture. This will make sure that for any width of the div it will have the height to match the aspect ratio of the picture so it won't be stretched or cropped. make sure to use background-size:contain.
  2. Set background-size to cover so there will automatic crop on the image but it would fit all sizes of the div. Tip: you can adjust the background-position property to make sure the part that you care about most in the picture is visible for example center center.

If you just care about the picture being shown properly go with the second option. However, if you have content inside that div or the size of the div is not under your control go with the first.

huangapple
  • 本文由 发表于 2023年5月10日 21:20:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76218955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定