Is it possible to tell the code to position by the center point of an element, rather than by the top-left point? If my parent element has
width: 500px;
and my child element has
/*some width, for this example let's say it's 200px*/ position: absolute; left: 50%;
one would assume that based on the 50%
positioning, the child element will be in the middle of the parent, leaving 150px
of free space on each side. However, it is not, since it is the top-left point of the child that goes to 50%
of the parent's width, therefore the whole child's width of 200px
goes to the right from there, leaving 250px
of free space on the left and only 50px
on the right.
So, my question is, how to achieve center positioning?
I found this solution:
position: absolute; width: 200px; left: 50%; margin-left: -100px;
but I don't like it because you need to edit it manually for each element's width - I would like something that works globally.
(For example, when I work in Adobe After Effects, I can set a position for an object and then set specific anchor point of that object that will be put to that position. If the canvas is 1280px
wide, you position an object to 640px
and you choose the center of the object to be your anchor point, then the whole object will be centered within the 1280px
wide canvas.)
I would imagine something like this in CSS:
position: absolute; left: 50%; horizontal-anchor: center;
Similarly, horizontal-anchor: right
would position the element by its right side, so the whole content would be to the left from the point of its parent's 50%
width.
And, the same would apply for vertical-anchor
, you get it.
So, is something like this possible using only CSS (no scripting)?
Thanks!
transform-origin lets you re-position the anchor point from the default center of the element. You can set the origin using real units like px or rem . You can also use percentages for X and Y. Or use keywords: left and right for X-axis, top and bottom for the Y-axis, and center for either/or.
You have to give your anchor a the rule display: block; . Anchors are inline elements per default. If you give an element position: absolute , you take it out of so-called normal document flow.
If the element must be absolutely positioned (so, margin: 0 auto;
is of no use for centering), and scripting is out of the question, you could achieve this with CSS3 transforms.
.centered-block { width: 100px; left: 50%; transform: translate(-50%, 0); position: absolute; }
See this fiddle for some examples. The important parts: left: 50%;
pushes block halfway across its parent (so its left side is on the 50% mark, as you mentioned). transform: translate(-50%, 0);
pulls the block half it's own width back along the x-axis (ie. to the left), which will place it right in the center of the parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With