我一直在使用:之前或之后的CSS技巧(在本文中解释:http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-multiple-borders-with-simple-css/)来实现多个边框和背景。它在div
元素上效果很好,但我注意到它根本不适用于图像。
这是我的代码:
.author img {
position: absolute;
left: 10px;
background-color: #fff;
padding: 3px;
border: 1px solid #d0d0d0;
width: 48px;
}
.author img:before {
content: '';
display: block;
width: 80px;
height: 16px;
position: absolute;
top: -17px; left: 0;
background: red;
}
有没有办法在图像上使用这个技巧,还是我必须在另外的div中包装我的图像?
答案 0 :(得分:7)
您必须包装img
,因为img
不能包含伪元素。在CSS中使用:before
和:after
时,概念上生成的是这种类型的结构(例如,带有div
;注意,这只是为了说明正在做什么,没有创建实际的html元素):
<div><pseudo-element:before />Actual div content<pseudo-element:after /></div>
将伪元素放在里面元素中。但是img
标记(和input
标记以及其他没有结束标记的非容器)没有“内容”的位置,包括伪元素生成的内容。
答案 1 :(得分:1)
这在DIV中工作正常,但IMG无法工作,因为它与应用内边框的区域重叠。幸运的是,有一个非常简单的解决方法:在DIV中包含IMG。
<div><img src="pic.jpg" alt="1" height="200" width="200" /></div>
并应用样式:
img {border: 2px solid red;}
div {border: 3px solid black; width:204px; height:204px;}
虽然您不需要在HTML中明确设置img高度/宽度,但仍需要知道它们是什么,因为DIV高度/宽度的计算如下:div h = img h + img borderx2; div w = img w + img borderx2