Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim word accorddingly to screen width

I have got a space on my navbar that brings an title. What I would like to do is: On a desktop screen it shows: "Title is too long for a mobile screen" On a mobile screen: "Title is too long..."

I have already done that detecting if it is a mobile screen and using str_limit("Title is too long for a mobile screen", 17) to trim the sentence.

But my problem is: There's plenty of different sizes of mobile phones and I would like to do it fitting the screen width and that includes if the user turns the screen to paisage. Anybody have an idea?

like image 235
dante Avatar asked Aug 05 '16 13:08

dante


2 Answers

You can achieve this with CSS alone by setting the overflow property to hidden, the text-overflow property to ellipsis and the white-space property to nowrap. This way, the text within the element will be trimmed when it's too small to fit the space available to it, without having to "sniff" for the screen size.

h1{
  background:#000;
  color:#fff;
  font-family:sans-serif;
  overflow:hidden;
  padding:5px;
  text-overflow:ellipsis;
  white-space:nowrap;
  width:50%;
}
<h1>This title might be too long to fit your screen</h1>
like image 107
Shaggy Avatar answered Sep 30 '22 19:09

Shaggy


i would prefer a css solution, because you have do a lot of calculations to get the length of the text in pixels ...

<span style="text-overflow: ellipsis">Title is too long for a mobile screen</span>

Example here: http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_text-overflow_hover

HTH

like image 41
Oliver Avatar answered Sep 30 '22 18:09

Oliver