2013-10-03 77 views
28

我想使用css在我的内容div中的所有图像上添加一个白色边框。页眉和页脚div区域中的图像不应受到影响。我如何实现这一目标?看下面的示例图片。网页上有不同尺寸的图片。图像与CSS的内部边界?

见图片:

Image with inner border

+2

在这里看到:HTTP://计算器。com/questions/9051228/css-internal-border 而你想要的工作解决方案: http://jsfiddle.net/ThinkingStiff/bNmzB/ –

+0

@EricHotinger这些答案只适用于一个坚实的“背景”,而不是一种模式。 – cimmanon

+0

@cimmanon - 他没有坚实的背景吗?我看不到任何图案。 –

回答

61

你可以做到这一点,而无需额外的元素或伪元素:

http://cssdeck.com/labs/t6nd0h9p

img { 
    outline: 1px solid white; 
    outline-offset: -4px; 
} 

IE9 & 10不支持的轮廓印性质,但在其他方面的支持还是不错的:http://caniuse.com/#search=outline

不需要知道图像的尺寸替代的解决方案:

http://cssdeck.com/labs/aajakwnl

<div class="ie-container"><img src="http://placekitten.com/200/200" /></div> 

div.ie-container { 
    display: inline-block; 
    position: relative; 
} 

div.ie-container:before { 
    display: block; 
    content: ''; 
    position: absolute; 
    top: 4px; 
    right: 4px; 
    bottom: 4px; 
    left: 4px; 
    border: 1px solid white; 
} 

img { 
    vertical-align: middle; /* optional */ 
} 
+0

尽管存在向后兼容性问题,但我仍喜欢这种方式。好一个。 –

+0

这将是我的首选选项,但我们主要是Internet Explorer内部。有没有其他的例如使用JavaScript?其他例子似乎都要求您指定图像大小。我想这会自动应用于所有图像。 – user2369812

+0

这可能是一个更好的问题,作为一个新问题提出。从本质上讲,你需要做其他答案正在做的事情:动态创建一个额外的元素并将边界应用到该元素上。我添加了一个替代解决方案,它使用了一个附加元素,并且不需要知道图像的尺寸。如果是我,我不会为了支持这些浏览器而经历这些环节,因为这只是一个小小的美化效果。 – cimmanon

0

无论DIV ID或类,你可以简单地添加

#yourDivIDExample { 
... 
} 

#yourDivIDExample img{ 
border:1px solid #ffffff; 
} 

这将创建在div本身的图像周围的边框..相同的作品类或全球规则也..

img { 
border:1px solid #ffffff; 
} 
1

你可以试试这个:

HTML:

<div class="image"> 
    <div class="innerdiv"> 

    </div> 
</div> 

的CSS:

.image 
{ 
    width: 325px; 
    height: 239px; 
    background:url(http://www.modernvice.com/files/images/backgrounds/_Zoom/black-pony.jpg) 0 0 no-repeat; 
    padding: 10px; 
} 

.innerdiv 
{ 
    border: 1px solid white; 
    height:100%; 
    width: 100%; 
} 

jsFiddle

希望这是你的意思:)

0

你可以做这样的事情DEMO

的HTMl

<div class="imgborder"> 
    <div class="in-imgborder"> 

    </div> 
</div> 

CSS

.imgborder { 
    width: 300px; 
    height: 300px; 
    position: relative; 
    background: url(http://placekitten.com/300/300) no-repeat; 
} 
.in-imgborder { 
    width: 290px; 
    height: 290px; 
    position: absolute; 
    top: 4px; 
    left: 4px; 
    border: 1px solid red; 
} 
0

我用box-shadow: insetworks with IE11 and up解决了这个问题。我想要在图像周围的边角处有一个边框,但这个例子的边界为10px。它需要父母div:before:after元素,但处理得很好。

.image { 
    width: 100%; 
    height: auto; 
} 

.image__wrapper { 
    position: relative; 
} 

.image__wrapper:before { 
    content: ''; 
    position: absolute; 
    top: 10px; 
    bottom: 10px; 
    left: 10px; 
    right: 10px; 
    box-shadow: inset 0 0 0 3px red; 
} 

CodePen Demo