我想知道是否有可能描绘一个 1px 的方形轮廓,在一个 div 中插入一个特定的距离。目前,CSS 和 HTML 看起来像这样
.object {
width: 100px;
height: 100px;
background-color: red;
color: white;
padding: 5px;
}
<div class="object">
Hello World!
</div>
结果是:
http://i.imgur.com/qdB0yb6.png
预期的结果是这样的:
最佳答案
方法#01:
您可以绘制outline
并使用outline-offset
属性。
Note:
outline-offset
is not supported by IE.
.object {
outline: solid #fff 1px;
outline-offset: -5px;
width: 100px;
height: 100px;
background-color: red;
color: white;
margin: 5px;
padding: 10px;
}
<div class="object">
Hello World!
</div>
方法#02:
您可以使用:before
或:after
伪元素绘制轮廓或从四面延伸的背景
。
.object {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #fff;
color: white;
padding: 5px;
margin: 10px;
}
.object:before {
background-color: red;
position: absolute;
content: '';
left: -5px;
right: -5px;
top: -5px;
bottom: -5px;
z-index: -1;
}
<div class="object">
Hello World!
</div>
方法#03:
您可以使用 css3 绘制多个背景图像 linear-gradient()
.以下是必要的 CSS:
div {
background-image: linear-gradient(to right, white, white),
linear-gradient(to bottom, white, white),
linear-gradient(to right, white, white),
linear-gradient(to bottom, white, white),
linear-gradient(to right, red, red);
background-repeat: no-repeat;
background-size: calc(100% - 10px) 1px, 1px calc(100% - 10px), calc(100% - 10px) 1px, 1px calc(100% - 10px), 100% 100%;
background-position: 5px 5px, top 5px right 5px, bottom 5px right 5px, 5px 5px, 0 0;
}
.object {
width: 100px;
height: 100px;
background-image: linear-gradient(to right, white, white),
linear-gradient(to bottom, white, white),
linear-gradient(to right, white, white),
linear-gradient(to bottom, white, white),
linear-gradient(to right, red, red);
background-repeat: no-repeat;
background-size: calc(100% - 10px) 1px, 1px calc(100% - 10px), calc(100% - 10px) 1px, 1px calc(100% - 10px), 100% 100%;
background-position: 5px 5px, top 5px right 5px, bottom 5px right 5px, 5px 5px, 0 0;
color: white;
padding: 10px;
}
<div class="object">
Hello World!
</div>
关于html - 使用 CSS 绘制一条方形线,插入到一个 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41937806/