CSS如何实现div背景图完整显示、避免被挤压?
问题描述
我的网站中有一个<div>,其内部嵌套了另一个div,用于展示大号标题和小号副标题,预期效果如下:
但实际运行效果如下:
可以看到背景图被严重挤压,不清楚该如何调整才能展示更完整的背景图,以下是对应的代码:
CSS代码
* { font-family: Oxygen; margin: 0px; } #s1 { background-image: url(https://images.pexels.com/photos/1388069/pexels-photo-1388069.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260); background-repeat: no-repeat; background-size: cover; } #s2 { text-align: center; padding-top: 40px; padding-bottom: 40px; } #sf1 { font-size: 40px; line-height: 1.25em; } #sf2 { font-size: 20px; } #sf3 { font-size: 30px; }
HTML代码
<div id="s1"> <div id="s2"> <div id="s3"> <h1 id="sf1">Rechtsanwalt Thomas FORELL</h1> <h2 id="sf2">Ihre Anwaltskanzlei in Leun, Bamberg und Burbach</h2> </div> <div> <h3 id="sf3">Arbeitsrecht • Scheidungsrecht • Verkehrsstrafrecht • Ordnungswidrigkeitenrecht • Vertragsrecht</h3> </div> </div> </div>
解决方案
背景图被挤压的核心原因是承载背景的#s1元素没有设置固定/最小高度,高度完全由内部文本内容的高度+上下padding决定,总高度太小导致background-size: cover只能裁切显示背景图的极小部分,可按以下方案调整:
- 给
#s1添加最小高度限制,数值根据你想要的展示效果调整即可,同时可以调整背景图定位,默认左上角对齐,改成居中对齐能展示背景图的核心区域,示例修改如下:
#s1 { background-image: url(https://images.pexels.com/photos/1388069/pexels-photo-1388069.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260); background-repeat: no-repeat; background-size: cover; /* 新增以下属性 */ min-height: 500px; background-position: center; }
- 如果需要适配不同屏幕尺寸,可以把
min-height的单位换成vh,比如设置min-height: 60vh让它始终占据视口60%的高度,适配性更好。 - 如果不希望背景图被裁切,可以把
background-size: cover改成background-size: contain,但该属性会在元素宽高比和图片不一致时出现留白,可根据视觉需求选择。
内容的提问来源于stack exchange,提问作者Tknoobs
相关产品推荐
相关产品推荐

