.dice#dice1 {
position: absolute;
top: 20%;
left: 45%;
transform: translateX(-55%);
}
.dice#dice2 {
position: absolute;
top: 20%;
right: 45%;
transform: translateX(55%);
border: 1px solid blue;
}
The above code is resulting in the following:
Although I'm using this code I'm a little bit confused as to how the absolute left and right work with translate...
Can anyone please help me understand this?
The part that I suspect is throwing you is that the transformX
percentage is the percentage of the width of the positioned element itself , whereas the top/left are percentages of the parent positioning context element.
.dice#dice1 {
position: absolute;
top: 20%;
left: 45%;
transform: translateX(-55%);
}
Consider this case when:
The element is positioned with its top at 20px, its left at 45px, because that's 20% and 45% of the parent, respectively.
The transformX
then moves the element left 5.5px, which is 55% of 10px, the element's own width.
When using percentage, left
/ right
/ up
/ down
position an element relative to the container and transform: translate()
positions an element relative to its own dimensions.
So, left: 50%
is half way across the container and transform: translateX(50%)
is half of the elements width.
When an element is position: absolute
, the body
becomes the container, unless you add position: relative
to the parent.
From your code it can be inferred that first you are absolutely positioning the two div
, here dice1 and dice2 , such that it's 20% from the top and 45% from the right.
Next after positioning the two div at the same place, you are translating 55% from the current position, one along the positive x direction and the other along the negetive x direction.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.