英文:
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
<div class="blog-img" style="background-image: url('{{ $blog->imgUrl }}');"></div>
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
你有两个选择,据我所见:
- 在与图片相匹配的 div 上设置
aspect-ratio
,以确保 div 的任何宽度都具有与图片相匹配的高度,从而不会被拉伸或裁剪。确保使用background-size:contain
。 - 将
background-size
设置为cover
,这样图像将自动裁剪,但适合 div 的所有尺寸。提示:您可以调整background-position
属性,以确保图片中您最关心的部分可见,例如center center
。
如果您只关心图片正确显示,请选择第二个选项。但是,如果 div 内有内容或者 div 的大小不受您控制,请选择第一个选项。
英文:
You have two options as far as I see it:
- 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 usebackground-size:contain
. - Set
background-size
tocover
so there will automatic crop on the image but it would fit all sizes of the div. Tip: you can adjust thebackground-position
property to make sure the part that you care about most in the picture is visible for examplecenter 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论