How to use transform:translateX to move a child element horizontally 100% across the parent
css, css-transforms, css-transitions, html
Solution
With the recent addition of Size Container Queries it is now possible to do this by setting the `container-type` property to `inline-size` in the parent and then translating the child element by 100cqw - 100% where 100cqw is the full width of the parent and 100% is the width of the child.
#parent {
position: relative;
width: 300px;
height: 100px;
background-color: black;
container-type: inline-size;
}
#child {
position: absolute;
width: 20px;
height: 100px;
background-color:red;
transform: translateX(calc(100cqw - 100%));
}
<div id="parent">
<div id="child">
</div>
Problem
All, I'd like to be able to use `translateX` to animate a child element 100% of the way across it's parent (i.e., from the left edge to the right edge). The challenge is that percentages in `translateX` refer to the element itself, not the parent. So, for example, if my html looks like this: ``` <div id="parent"> <div id="child"> </div> ``` And my CSS like this (vendor-prefixes omitted): ``` #parent { position: relative; width: 300px; height: 100px; background-color: black; } #child { position: absolute; width: 20px; height: 100px; background-color:red; transform: translateX(100%); } ``` This doesn't work - the child only moves 20px (100% of itself), not all the way across the parent. (You can see this on jsfiddle): I can do this: ``` #child { position: absolute; width: 20px; height: 100px; background-color:red; -webkit-transform: translateX(300px) translateX(-100%); transform: translateX(300px) translateX(-100%); } ``` This works (seen here again on jsfiddle), because it first moves the child 300px (the full width of the parent), minus 20px (the width of the child). However, this depends on the parent having a fixed, known pixel dimension. However, in my responsive design - I don't know the width of the parent, and it will change. I know that I can use `left:0` and `right:0`, but the animation performance of left/right is much worse than translateX (Thanks Paul Irish!). Is there a way to do this? Thanks in advance.