简体   繁体   中英

How to give an element space from the opposite/same side without using right and left direction in CSS?

Suppose, I have two buttons in HTML-

<button class="save">Save</button>
<button class="cancel">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.

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

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;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM