CSS内边框?

7

我用纯CSS创建了左侧的按钮。它是一个包含在另一个div中的div。然而,右侧的三个按钮是标签上的background属性。我这样做是为了模拟一个滑过效果,遵循这里的说明。

enter image description here

现在,有没有一种方法可以使用CSS将第一个按钮中的内部边框添加到其他三个按钮中?

可在此处查看代码示例。


1
把它直接添加到图像本身不是更容易吗? - Brettski
1
首先,你怎么做呢?其次,假设它不是。 - john
4个回答

10

根据盒子模型,内边距在内容边框之间。您可以按以下方式设置图像样式:

 .img-btn {
     background: #FFF; // inner border color
     padding: 2px; // inner border width
     border: 2px solid #[yourgreen]; // outer border
 }

即使是对于纯CSS按钮,你也不需要额外的div来完成这个操作。以下样式适用于图像作为背景图片的情况:

.img-btn {
    background: #FFF url('your.img') no-repeat;
    padding: 2px;
    border: 2px solid #[yourgreen];
    width: [image width];
    height: [image height];
    background-position: center center;
}

以下是双边框的示例DEMO


这里设置background的颜色和图片不会冲突吗? - john
@awfullyjohn 不应该,你可以同时拥有背景颜色和背景图片。我会更新答案。 - calebds

5
您不需要两个 <divs> 和一个 <a> 来创建按钮。您可以使用单个 <a> 完成它。对于图片和按钮,您可以使用 box-shadow 属性来创建外部边框。将 background-images 居中显示在 <img> 元素中。

演示:http://jsfiddle.net/ThinkingStiff/bNmzB/

输出:

enter image description here

HTML:

<a id="add" href="#">Add To Cart</a>
<img id="facebook" class="icon" />
<img id="twitter" class="icon" />
<img id="email" class="icon" />

CSS:

#add {
    background-color: #9bc9c7;
    border: 1px solid white;
    box-shadow: 0 0 0 2px #9bc9c7;
    color: white;
    display: inline-block;
    font: normal 13px/25px Helvetica, Arial, Sans Serif;
    height: 25px;
    margin-right: 6px;
    text-align: center;
    text-decoration: none;
    text-transform: uppercase;
    width: 120px;
    vertical-align: top;
}

#add:hover {
    background-color: #eabeb2;
    box-shadow: 0 0 0 2px #eabeb2;
}

.icon {
    background-color: rgb( 155, 201, 199 );
    border: 1px solid white;
    box-shadow: 0 0 0 2px rgb( 155, 201, 199 );
    height: 25px;
    margin-right: 3px;
    width: 25px;       
}

谢谢。我会这样开始做 +1。 - john
聪明!值得注意的是,box-shadowCSS3的一部分,因此浏览器兼容性可能会成为一个问题。特别是,在IE 8及以下版本中不支持它(https://developer.mozilla.org/en/CSS/box-shadow)。 - Joe White
1
@awfullyjohn 刚刚看了你的演示链接。你可以只用锚点来做按钮。我已经更新了上面的代码。 - ThinkingStiff

0
假设您无法直接修改图标图像,只需以与“添加到购物车”相同的方式将它们包装在 div 中。您还需要使用以下内容之一:
background-position: center center;

为了确保图标在较小的img中保持居中,和/或。
background-size: 24px 24px;

将背景缩小一点,这样白色边框就不会与符号重叠。


0
使用与按钮相同的方法 - 将图标视为内部 div 的背景图像。因此,您应该有一个带有一些内边距的 div,在其中有一个带有白色边框的内部 div(在您的情况下是 img),以及一个背景图像(即图标)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接