Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

html - CSS crop string in the middle

I have a big filename that I'm cropping using css text-overflow: ellipsis.

<style>
   #fileName {
      width: 100px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
  }
</style>
<div id="fileName"> This is the big name of my file.txt</div>

So I have this output

This is the bi...

But I want to preserve the file extension and have something like this

This is the... le.txt

Is it possible only using CSS?

Since my files are always txt, I've tried to use text-overflow: string, but it looks like it only works on Firefox:

 text-overflow: '*.txt';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a clean CSS solution using the data-* attribute and two ::after pseudo-elements. I also added an optional hover and show all text (the #fileName::after pseudo element needs to be removed when the full text is shown).

Example 1

#fileName {
  position: relative;
  width: 100px;
}

#fileName p {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

#fileName:after {
  content: attr(data-filetype);
  position: absolute;
  left: 100%;
  top: 0;
}


/*Show on hover*/

#fileName:hover {
  width: auto
}

#fileName:hover:after {
  display: none;
}
<div id="fileName" data-filetype="txt">
  <p>This is the big name of my file.txt</p>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...