边框外部绝对定位

时间:2016-10-21 14:02:01

标签: html css html5 css3

当我在一个相对元素中绝对定位一个元素时,坐标是从容器的边缘计算出来的,而不考虑边界(相当于从边框内侧定位的东西。)

有没有办法定位元素但是从边框的外侧?

例如:如果我有一个没有边框的红色正方形(如第一个),则文本会粘贴到容器的左上角,因为它有<body>。但是第二个方块中的文字仍然有top:0; left:0,但边框将文字推到广场内:

&#13;
&#13;
top:0;left:0
&#13;
.box {
  position:relative;
  width:150px;
  height:150px;
  background:red;
  box-sizing:border-box;
  margin:10px;
  float:left;
}

.box-bordered {
  border:25px solid rgba(0,0,0,0.1);
}

.text {
  position:absolute;
  top:0;
  left:0;
  color:white;
}
&#13;
&#13;
&#13;

我想要的是让文字一直贴在彩色区域的左上角。那可能吗?怎么可能呢?

  

注意:出于好奇,这更像是一个理论问题;我知道有一些替代方案可以起作用(至少在视觉上),比如使用负边距,负定位值或插入<div class="box"> <div class="text">Text</div> </div> <div class="box box-bordered"> <div class="text">Text</div> </div>

     

&#13;
&#13;
box-shadow
&#13;
.box {
  position:relative;
  width:150px;
  height:150px;
  background:red;
  box-sizing:border-box;
  margin:10px;
  float:left;
}

.box-shadow {
  box-shadow:inset 0 0 0 25px rgba(0,0,0,0.1);
}

.text {
  position:absolute;
  top:0;
  left:0;
  color:white;
}
&#13;
&#13;
&#13;

     

但是我想知道它是否可以在保持边界的同时做到。

4 个答案:

答案 0 :(得分:2)

没有箱子阴影,但也没有相当的边界。怎么样?

&#13;
&#13;
.box {
  position:relative;
  width:150px;
  height:150px;
  background:red;
  box-sizing:border-box;
  margin:10px;
  float:left;
}

.box:before {
  content:" ";
  border:25px solid rgba(0,0,0,0.1);
  height:100%;
  z-index:1;
  position:absolute;
  box-sizing:border-box;
  width:100%;
}

.text {
  position:absolute;
  top:0;
  left:0;
  color:white;
  z-index:2;
}
&#13;
<div class="box">
  <div class="text">Text</div>
</div>
&#13;
&#13;
&#13;

或以盒装边框:之后如果要将类保留在div元素

答案 1 :(得分:1)

我想到的唯一两个解决方案是:

  1. 设置负边距等于.text
  2. 上的边框宽度
  3. 在左右属性中使用负值。
  4. &#13;
    &#13;
    .box {
      position:relative;
      width:150px;
      height:150px;
      background:red;
      box-sizing:border-box;
      margin:10px;
      float:left;
    }
    
    .box-bordered {
      border:25px solid rgba(0,0,0,0.1);
    }
    
    .text {
      position:absolute;
      top:0;
      left:0;
      color:white;
      margin: -25px;
    }
    .text2 {
      position:absolute;
      top: -25px;
      left:-25px;
      color:white;
    }
    &#13;
    <div class="box box-bordered">
      <div class="text">Text</div>
    </div>
    
    <div class="box box-bordered">
      <div class="text2">Text</div>
    </div>
    &#13;
    &#13;
    &#13;

答案 2 :(得分:0)

我不知道您是否考虑过它,但box-shadow有默认保证金。将其设置为0,即可获得所需的结果。

.box {
  position:relative;
  width:150px;
  height:150px;
  background:red;
  box-sizing:border-box;
  margin:10px;
  float:left;
}

.box-shadow {
  box-shadow:inset 0 0 0 25px rgba(0,0,0,0.1);
  margin: 0;
}

.text {
  position:absolute;
  top:0;
  left:0;
  color:white;
}
<div class="box box-shadow">
  <div class="text">Text</div>
</div>

答案 3 :(得分:0)

正如您在中心所看到的那样,100 x 100区域是放置文本内容的区域。每个内容都将根据边距,边框和填充进行计算。

Element Outlines

因此,我没有看到你所提到的不使用负边距或插入框的解决方案,这是对原始问题的某种修复。