问题
<div style="width:100px; overflow:hidden; text-align:right;" id="pathdiv">
<script>
document.getElementById("pathdiv").innerHTML="long/path/to/file"
</script>
My goal is to show a long absolute path right aligned in a relatively narrow div, in a way that its beginning is cut down ( so that the interesting part of the path is shown ). The above code makes the text right aligned if it fits in the div, cuts it if it does not fit, but unfortunately it cuts the end of it, not the beginning.
I could trim the string if it is too long manually, but then I have to calculate somehow how many characters make it fit ( unclear ).
Is their any straightforward way to achieve my goal ( either with CSS or otherwise )?
回答1:
<div style="width:100px; overflow:hidden; text-align:right;text-overflow:ellipsis; direction:rtl" id="pathdiv">
<script>
document.getElementById("pathdiv").innerHTML="long/path/to/file"
</script>
Adding direction(rtl) would work.
回答2:
You can use a span inside the div and make it position:absolute
and right:0
. In this case you will obtain what you need.
add white-space:nowrap;
if you will have space in the content to avoid line break
document.querySelector("#pathdiv span").innerHTML="very/very/very-long/path/to/file"
#pathdiv {
width: 100px;
overflow: hidden;
text-align: right;
position: relative;
}
#pathdiv:before {
content:"A"; /* Hidden character to create the needed space*/
visibility:hidden;
}
span {
position: absolute;
white-space:nowrap; /* no needed for path (content) without any spaces*/
right: 0;
top: 0;
}
<div id="pathdiv">
<span></span>
</div>
Here is another way using flex and without adding span :
document.querySelector("#pathdiv").innerHTML = "very/very/very-long/path/to/file"
#pathdiv {
width: 100px;
overflow: hidden;
text-align: right;
display: flex;
justify-content: flex-end;
align-items: flex-end;
white-space: nowrap;
height: 20px;
}
<div id="pathdiv">
</div>
来源:https://stackoverflow.com/questions/47926246/how-can-i-align-text-to-the-right-in-a-div-so-its-beginning-is-cut-down-with-ove