Reputation: 18353
I'm trying to lay out a page using divs. I'm struggling because the reference point to a <div>
seems to be the top left. This is okay, until the div changes shape. Then, the position via the top left isn't suitable.
If you see http://jsfiddle.net/jdb1991/8Xb7L/, you will get a live example of
#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>
Is there a way, using CSS, to change the "reference point" of the square to be either the centre, or a different corner?
Upvotes: 6
Views: 7833
Reputation: 1599
Besides setting width and height to 0
, which might have some undesirable consequences, another possible solution would be to give a negative left margin equal to exactly half the full box width, and a negative top margin equal to exactly half the full box height, where full width/height = width/height + border + padding.
For the box in your fiddle, which has width/height of 100 pixels and a 1 pixel border, this would mean adding
margin-left: -51px;
margin-top: -51px;
Upvotes: 0
Reputation: 44181
You need to put the point
inside the square
, then give the square
position: relative
. The position of the point will then be relative to the square (i.e. left
will be the distance from the left edge of the square.)
#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>
If you want to use a different corner for positioning, use the right
or bottom
properties instead of left
or top
.
If you wish to position from the center, do what I suggested with the square, but give it a 0
width and height. The square will now be at the center and the point is positioned relative to it. Obviously you lose the width and height, so using percents for left
and top
won't work any longer.
Upvotes: 4