Html 背景图片边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12381721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:47:13  来源:igfitidea点击:

background image border

htmlcss

提问by stdcerr

Is there a css property to set a border around a background image? I've been searching for that but haven't found it, does it exist or am I left with needing to draw the line manually around my background images?

是否有 css 属性来设置背景图像周围的边框?我一直在寻找它,但没有找到它,它是否存在,或者我是否需要在我的背景图像周围手动绘制线条?

采纳答案by NullPoiиteя

This can be done by adding image in a div and than set the border of the div

这可以通过在 div 中添加图像然后设置 div 的边框来完成

<div style="border:1px solid red;float:left;">
   <div style="background:url("...");float:left;"></div>
<div>

回答by Scott Bartell

Without specific implementation details it's very difficult (if not impossible) to provide a solution that works in all cases. Here's a couple solutions with the constraints provided:

如果没有具体的实现细节,就很难(如果不是不可能的话)提供适用于所有情况的解决方案。这是提供了约束的几个解决方案:

Example 1 - Fixed Size

示例 1 - 固定大小

If you know the height and width of the background image you can do something like this:

如果您知道背景图像的高度和宽度,您可以执行以下操作:

HTML

HTML

<div class="bg"> </div>

CSS

CSS

div.bg {
  background-image: url('http://www.google.com/images/logo_sm.gif');
  border: 5px solid #000;
  width: 50px;
  height: 50px;
}

Working example: http://jsfiddle.net/WUHmw/

工作示例:http: //jsfiddle.net/WUHmw/

Example 2 - Repeating Background Image

示例 2 - 重复背景图像

If the background image repeats, you can do something like this:

如果背景图像重复,您可以执行以下操作:

HTML

HTML

<div class="bg">
   <p>Here is some text to on top of the background image.</p>
</div>

CSS

CSS

div.bg {
  background: url('http://i.imgur.com/ikxbnvc.png') repeat;
  border: 5px solid #000;
  box-sizing: border-box;
  width: 100%;
  height: 200px;
}

Working example: http://jsfiddle.net/pLz52/

工作示例:http: //jsfiddle.net/pLz52/

回答by omer

this can also be done using css drop-shadow https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/drop-shadow

这也可以使用 css drop-shadow https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/drop-shadow来完成

 <div class="box">
  <div class="bgImg"></div>
</div>

 .box {
     width:400px;
     height: 400px;
     display: flex;
     justify-content: center;
     align-items:center;
     border: 1px solid red;
       .bgImg{
        width: 300px;
        height: 300px;
        background: url('http://i.imgur.com/ikxbnvc.png');
        background-repeat: no-repeat;
        background-size: contain;
        background-position: center center;
        filter: drop-shadow(0 0 1px black);
    }
 }

http://jsfiddle.net/wtesuqjz/

http://jsfiddle.net/wtesuqjz/

the browser support is not perfect

浏览器支持不完善