3

I made a sidebar that collapses/opens with animation. The site can either be RTL or LTR.

.sidebar {
    max-width: 380px;
    width: 85%;
    height: 100%;
    position: fixed;
    z-index: 100;
    top: 0;
    inset-inline-start: 0;
    padding: 10px 20px;
    transform: translateX(100%);
    transition: transform 0.3s ease;
    
}

For the RTL website, I can use:

transform: translateX(100%);

and it will hide it, but on LTR, it will move it to the right side from the left.

I used inset-inline-start instead of right/left.

How can I then use translateX to hide the sidebar regardless of the dir attribute, so that on RTL it will hide it to the right side, and on LTR to the left.

I could use some manual setting like so:

:root {
  --sidebar-translate: -100%; /* move left off-screen */
}

/* RTL override */
:dir(rtl) {
  --sidebar-translate: 100%; /* move right off-screen */
}

and then:

transform: translateX(var(--sidebar-translate));

But maybe there's a better/cleaner way?

2
  • 1
    Ho would you define better or cleaner? Your current solution seems clear and simple. Commented Nov 16 at 20:36
  • Flow-relative transforms were proposed to the CSSWG as long ago as 2015 but it seems little progress has been made. Commented Nov 16 at 21:27

1 Answer 1

3

If I understand correctly, to your sidebar, you only want it to slide out to the right depending on if it is LTR or RTL.

To tell you the truth : translateX() doesn’t care if it's RTL or LTR.

Going to the left is always -100% and going to the right is always 100%.

CSS can’t automatically flip this around.

So the clean way is What you already did (using a css variable and :dir(rtl)) is honestly the best solution:

  • default is set to -100% (hidden to the left)

  • :dir(rtl) is an override set to 100% (hidden to the right)

Then you can do transform: translateX(var(--sidebar-translate));

That’s it CSS doesn’t have "magic" for logical transforms, so ... your solution is the right one.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, good to know! I thought I may have missed some logical translate rule! Do you think they're working on this for the next css update?
to be honest, i don't think so...Your approach will stay the recommended pattern for a while.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.