计算绝对位置的宽度

时间:2017-03-12 10:03:31

标签: css

我正在尝试使用calc(100%-4px)为我的计算宽度,但由于它是position:absolute,因此无效。

JSfiddle



article {
  background: linear-gradient(135deg, #FF9800, rgba(255, 235, 59, .91) 87%), url(http://ably.ir/Uploads/SQL%20Server/SQL-Server-Integration-Services-SSIS-Tutorial.jpg);
  background-position: center center;
  color: #263238;
  height: 150px;
  width: 400px;
  position: relative;
}

article:after {
  content: "";
  width: calc(100%-4px);
  height: calc(100%-4px);
  background: #263238;
  position: absolute;
  left: 2px;
  top: 2px;
}

<article class="col-md-12">
  <h2>something</h2>
</article>
&#13;
&#13;
&#13;

this is what i want

3 个答案:

答案 0 :(得分:2)

左/右和上/下尺寸比父母尺寸小2px的替代解决方案是使用right: 2pxbottom: 2px到您的绝对位置元素:

article {
  background: linear-gradient(135deg, #FF9800, rgba(255, 235, 59, .91) 87%), url(http://ably.ir/Uploads/SQL%20Server/SQL-Server-Integration-Services-SSIS-Tutorial.jpg);
  background-position: center center;
  color: #263238;
  height: 150px;
  width: 400px;
  position: relative;
}

article:after {
  content: "";
  /*width: calc(100% - 4px);*/
  /*height: calc(100% - 4px);*/
  background: #263238;
  position: absolute;
  left: 2px; right:2px;
  top: 2px; bottom:2px;
}
<article class="col-md-12">
  <h2>something</h2>
</article>

这具有更好的性能(因为不需要重新计算特殊事件的属性)和更好的浏览器支持

答案 1 :(得分:1)

你没有正确写出来 你需要在运算符“ - ”

之间添加空格

article {
  background: linear-gradient(135deg, #FF9800, rgba(255, 235, 59, .91) 87%), url(http://ably.ir/Uploads/SQL%20Server/SQL-Server-Integration-Services-SSIS-Tutorial.jpg);
  background-position: center center;
  color: #263238;
  height: 150px;
  width: 400px;
  position: relative;
}

article:after {
  content: "";
  width: calc(100% - 4px);
  height: calc(100% - 4px);
  background: #263238;
  position: absolute;
  left: 2px;
  top: 2px;
}
<article class="col-md-12">
  <h2>something</h2>
</article>

答案 2 :(得分:1)

在calc函数中添加值和运算符之间的空格

calc(<value> <operator> <value>)

例如

width: calc(100% - 4px);
height: calc(100% - 4px);