【发布时间】:2017-03-03 21:14:41
【问题描述】:
当我在相对元素中对元素进行绝对定位时,坐标是从容器的边缘计算出来的,而不考虑边界(这相当于从边界的内侧定位。)
除了从边框的外侧定位元素之外,还有其他方法吗?
例如:如果我有一个没有边框的红色方块(如第一个),则文本会粘在容器的左上角,因为它有top:0; left:0。但是第二个方块里面的文字还有top:0;left:0,但是边框把方块里面的文字推了进去:
.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>
我想要的是让文本一直粘在彩色区域的左上角。那可能吗?怎么可能?
注意:这更多是出于好奇而提出的理论问题;我知道有一些替代方法(至少在视觉上)可以使用,例如使用负边距、负定位值或插入
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>但我想知道是否可以在保持边界的同时做。
【问题讨论】:
-
请记住,只有在 box-sizing: border-box; 的情况下,边框才能进入内部。属性已设置。
-
两种情况下都有
box-sizing: border-box -
如果稍微改一下 html 不打扰你,你可以看看这个jsfiddle.net/87hurwnu 或者不改html就更好了jsfiddle.net/87hurwnu/1