Home > Software design >  How to give an element space from the opposite/same side without using right and left direction in C
How to give an element space from the opposite/same side without using right and left direction in C

Time:12-19

Suppose, I have two buttons in HTML-

<button >Save</button>
<button >Cancel</button>

I want to give the cancel button a margin of 10px from the left side when it's LTR and 10px from the right side when it's RTL.

Using Javascript, I can do this very well, like this-

let cancel = document.querySelector('.cancel');
// Suppose, the "direction" is an input variable.
cancel.style[direction == 'ltr' ? 'margin-left' : 'margin-right'] = '10px';

If I give an example, in the following CSS properties, we only use start and end values and they adjust the element automatically to the left and right direction according to the page direction.

text-align: end;
text-align: start;
justify-content: start;
align-items: end;

Something like the above, I want to know if there is any way to set space (either margin or padding) from opposite/same directions without mentioning right and left in CSS.

Many modern frameworks like Vuetify handle this kind of case (set space according to LTR and RTL) from their inbuilt helper classes (though JS or any CSS property must run behind those concepts) but the question is, is this possible using CSS only.

CodePudding user response:

Try margin-inline-start: (some value);, this automatically changes when you switch to RTL

CodePudding user response:

Option 1: Inline margins

.cancel {
  margin-inline-start: 10px;
  writing-mode: horizontal-tb;
  direction: rtl;
}

Option 2: before pseudo-class

.cancel::before {
  content: "";
  display: inline-block;
  width: 10px;
}
  • Related