Reputation: 15984
I have a div that it's direction is determined by the content it hosts (using dir="auto"
). I would like to use CSS (if it's impossible than javascript) to determine the direction and change the absolute position of the delete span accordingly.
see here in this fiddle: https://jsfiddle.net/psjgsnby/
<div dir="auto" class="item">
text
<span>x</span>
</div>
<div dir="auto" class="item">
מימין לשמאל
<span>x</span>
</div>
css:
.item {
position: relative;
width: 200px;
}
.item span {
position: absolute;
right: 0;
top: 0;
}
i'm looking for something like this selector:
.item span:dir(rtl) {
right: auto;
left: 0;
}
but something that works cross-browser (the above works only for firefox)
Upvotes: 7
Views: 1198
Reputation: 64164
If you change the display of the container to flex, this is easily achievable. You just need justify-content: space-between:
The CSS is even more compact that what you had:
.item {
position: relative;
display: flex;
width: 200px;
justify-content: space-between;
}
<div dir="auto" class="item">
text
<span>x</span>
</div>
<div dir="auto" class="item">
מימין לשמאל
<span>x</span>
</div>
Upvotes: 0
Reputation: 62556
Using dir="auto"
gives the browser the ownership on detecting which direction to use, based on the content of the element.
Note that different browsers might give different results, based on implementation.
The dir=auto
actually tells the browser to:
look at the first strongly typed character in the element and work out from that what the base direction of the element should be. If it's a Hebrew (or Arabic, etc.) character, the element will get a direction of rtl. If it's, say, a Latin character, the direction will be ltr.
In CSS
you don't really have an option to check this, but if you want to use javascript you can try to do exactly the same. Find the first character that is strongly typed, and based on that use the relevant direction. The only question you got here is which languages you want to support.
Upvotes: 2
Reputation: 2273
I found a solution but its very far from your code. Its base on display: table
because we need a dynamic direction flow for every element.
Don't forget, you can change the vertical align for different positions.
.item {
display: table;
width: 200px;
height: 50px;
}
.item .btn,
.item .content {
display: table-cell;
}
.item .btn {
vertical-align: top;
}
.item .content {
width: 100%;
vertical-align: bottom;
}
<div dir="auto" class="item">
<span class="content">text</span>
<span class="btn">
x
</span>
</div>
<div dir="auto" class="item">
<span class="content">מימין לשמאל</span>
<span class="btn">
x
</span>
</div>
Upvotes: 1