Alvaro Montoro Alvaro Montoro - 1 month ago 24
CSS Question

Absolute positioning from border exterior

When I absolute-position an element inside a relative element, the coordinates are calculated from the edges of the container without taking into account the borders (what would be equivalent to positioning from the interior side of the border.)

Is there any way of positioning the element but from the exterior side of the border?

For example: if I have a red square (like the first one) without a border, the text sticks to the top left of the container because it has

top:0; left:0
. But the text in the second square still has
top:0;left:0
, but the border pushes the text inside the square:



.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;
}

<div class="box">
<div class="text">Text</div>
</div>

<div class="box box-bordered">
<div class="text">Text</div>
</div>





What I would like for it is for the text to keep sticking to the top left corner of the colored area. Is that possible? How could it be done?


Note: This is more of a theory question out of curiosity; I know there are alternatives that will work (at least visually) like using negative margins, negative positioning values or an inset
box-shadow
:



.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;
}

<div class="box box-shadow">
<div class="text">Text</div>
</div>





but what I would like to know if it it's possible doing while keeping the borders.

Answer

No box shadow but not quite border either. How about this?

.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;
}
<div class="box">
  <div class="text">Text</div>
</div>

or box-bordered:after if you want to keep the class on the div element