You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何偏移背景图仅显示下半部分(模拟overflow:hidden效果)

如何偏移背景图片,仅从父容器顶部显示图片下半部分

需求:让背景图片仅从父容器顶部区域显示图片的下半部分,上半部分隐藏,已知可通过background-position实现,需要具体操作方法。

现有代码:

.container{
    background-image: url(./images/bg-pattern-circles.svg);
    background-repeat: no-repeat;
    background-position: center top;
    padding: 10rem 2.5rem 8rem;
    position: relative;
    border-radius: 0 7rem 0 7rem;
    width: 100%;
    text-align: center;
    color: hsl(0, 0%, 100%);
    line-height: 1.5;
}

.container::before{
    content: '';
    width: 100%;
    height: 100%;
    background-image: linear-gradient(hsl(237, 17%, 21%), hsl(237, 23%, 32%));
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    border-radius: inherit;
}
<div class="container">
  <h3>State of the Art Infrastructure</h3>
  <p>With reliability and speed in mind, worldwide data centers provide the backbone for ultra-fast connectivity. This ensures your site will load instantly, no matter where your readers are, keeping your site competitive.</p>
</div>

解决方案

要实现仅显示背景图片的下半部分,可通过调整background-size和background-position的组合来实现,具体有两种常用方式:

方式一:利用百分比偏移(适配未知图片尺寸)

修改.container的背景属性:

.container{
    background-image: url(./images/bg-pattern-circles.svg);
    background-repeat: no-repeat;
    /* 向上偏移图片自身高度的50%,让图片中点对齐容器顶部,容器内仅显示下半部分 */
    background-position: center -50%;
    /* 保持图片原有比例,宽度自适应容器 */
    background-size: auto 100%;
    padding: 10rem 2.5rem 8rem;
    position: relative;
    border-radius: 0 7rem 0 7rem;
    width: 100%;
    text-align: center;
    color: hsl(0, 0%, 100%);
    line-height: 1.5;
}

方式二:放大背景图并定位(精准控制显示区域)

如果需要更精准的控制,可以将背景图高度放大为容器的2倍,再让图片顶部对齐容器顶部,这样容器内刚好显示图片的下半部分:

.container{
    background-image: url(./images/bg-pattern-circles.svg);
    background-repeat: no-repeat;
    background-position: center top;
    /* 将图片高度设为容器的2倍,宽度按比例自适应 */
    background-size: auto 200%;
    padding: 10rem 2.5rem 8rem;
    position: relative;
    border-radius: 0 7rem 0 7rem;
    width: 100%;
    text-align: center;
    color: hsl(0, 0%, 100%);
    line-height: 1.5;
}

原理说明

  • 背景图片超出容器范围的部分默认不会显示,无需额外设置overflow:hidden;
  • 方式一中的background-position: center -50%是将图片向上偏移自身高度的50%,使得图片的中点对齐容器顶部,容器内自然只显示图片的下半部分;
  • 方式二中的background-size: auto 200%把图片高度拉伸为容器的2倍,再配合background-position: center top,让图片顶部和容器顶部对齐,此时容器内刚好显示图片的下半段区域。

内容的提问来源于stack exchange,提问作者Innocent Victor Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 00:46:00