我正在尝试使用div来布局页面。我很挣扎,因为<div>
的参考点似乎是左上角。这没关系,直到div改变形状。然后,左上角的位置不合适。
如果您看到http://jsfiddle.net/jdb1991/8Xb7L/,您将获得
的实时示例#point { position: absolute; top: 50%; left: 50%; }
#square { border: solid black 1px; height: 100px; width: 100px; position: absolute; top: 50%; left: 50%; }
<div id="point">+</div>
<div id="square"></div>
有没有办法,使用CSS,将广场的“参考点”更改为中心或不同角落?
答案 0 :(得分:3)
您需要将point
放在square
内,然后提供square
position: relative
。然后,该点的位置将相对于正方形(即left
将是距正方形左边缘的距离。)
#point { position: absolute; top: 50%; left: 50%; }
#square { position: relative; border: solid black 1px; height: 100px; width: 100px; position: absolute; top: 50%; left: 50%; }
<div id="square">
<div id="point">+</div>
</div>
如果您想使用其他角落进行定位,请使用right
或bottom
属性,而不是left
或top
。
如果您希望从中心定位,请按照我对方块的建议进行操作,但要给它0
宽度和高度。方块现在位于中心,点相对于它定位。显然你会失去宽度和高度,因此使用left
和top
的百分比将不再有效。
答案 1 :(得分:0)
除了将宽度和高度设置为0
,这可能会产生一些不良后果,另一个可能的解决方案是给出一个负的左边距,恰好是整个框宽度的一半,并且负的上边距恰好等于整个盒子高度的一半,全宽/高度=宽度/高度+边框+填充。
对于小提琴盒子,宽度/高度为100像素,边框为1像素,这意味着要添加
margin-left: -51px;
margin-top: -51px;