在 css 中将背景图像设置为 div,并在左侧和右侧留下偏移量

Setting background image to div in css leaving an offset in left and right

我在 html 5 中有一组 div 具有 class 名称 submenuButton。我想使用 css 向这些 div 添加一个通用背景图像。我尝试了以下方法:

.submenuButton{
     background-image:url(images/but-up-center.png); 
     background-position: 5px 0px;
     background-repeat:repeat-x;
     background-size: contain;
}

这会设置 div 图像从左侧离开 5px 并延伸到按钮的末尾。但是我也想让这张图片在右边 5px 处结束。

那么,有人可以建议在 css 中可以做什么,以便在左侧和右侧都留下 5px space。

您可以结合使用 background-clip: content-box; 和 5 像素的左右填充。

这将为您提供以下代码:

.submenuButton{
    padding: 0 5px;
    background-image:url(images/but-up-center.png);
    background-repeat:repeat-x;
    background-size: cover;
    background-clip: content-box;
}

有关 background-clip 的更多信息,请访问 developer.mozilla.org

Example on jsFiddle

你可以用伪

.submenuButton {
    position: relative;
    border: 1px solid red;
    height: 100px;
    width: 200px;
}
.submenuButton::before {
    position: absolute;
    content: '';
    top: 0;
    left: 5px;
    right: 5px;
    height: 100%;
    background:url(http://placehold.it/200/) no-repeat center;
    background-size: cover;
}
<div class="submenuButton"></div>