简体   繁体   English

如何在div中将文本向右对齐,以使它的开头被溢出:隐藏?

[英]How can I align text to the right in a div so its beginning is cut down with overflow:hidden?

<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 ). 我的目标是显示一条较长的绝对路径,该绝对路径以相对狭窄的div对齐,以减少其开始的方式(以便显示路径的有趣部分)。 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. 上面的代码在div合适的情况下使文本右对齐,在不合适的情况下将其剪切,但是不幸的是,它剪切了文本的结尾而不是开头。

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 )? 他们是实现我的目标的直接方法(使用CSS还是其他方法)?

You can use a span inside the div and make it position:absolute and right:0 . 您可以在div内使用跨度,并将其position:absoluteright:0 In this case you will obtain what you need. 在这种情况下,您将获得所需的东西。

add white-space:nowrap; 添加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 : 这是使用flex而不增加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> 

 <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. 添加direction(rtl)将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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