html - 使用 CSS 绘制一条方形线,插入到一个 div 中

标签 html css

我想知道是否有可能描绘一个 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

预期的结果是这样的:

http://i.imgur.com/vnfFhmY.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/

相关文章:

c# - 不完整的视频流式传输到移动浏览器 - HTTP header

html - 为什么html元素只在所有css文件加载完成后才显示

javascript - 在 AngularJS 中,我可以添加一个也有 Angular 模板数据的 HTML block 吗?

Jquery + CSS 动画

javascript - 在表中显示多个复选框值

html - 将一个 ul 放在一个 div 中(在一个 div 中),它本身在页面上居中

javascript - JQuery 动画横幅

Css 剪辑路径圆

css - 如何使用 Less 自定义 Bootstrap 中网格的偏移选项

html - 滚动条没有激活?