I have a PHP-Webapp and a span, that looks something like this:
<span><?= $text ?></span>
I would like to make sure, that the span has only one line. So if the text is too long, I would like to not show the last words. Can I do that using HTML/CSS? Or 开发者_开发知识库do I have to shorten the text with PHP/Javascript?
How about this? (obviously you would set thewidth to whatever it needs to be on the page)
The text-overflow: ellipsis is CSS3 and will only be supported in modern browsers, so in older ones you will get a nasty mid-letter/word cut off at the end.
span{display: block; width: 100px; overflow: hidden; word-wrap: break-word; text-overflow: ellipsis;}
I recommend to you below code
span {
display: -webkit-box;
-webkit-line-clamp: 2; // <- you can change rows number
-webkit-box-orient: vertical;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
Here's a rough and not fully tested idea:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<style type="text/css"><!--
p{
margin: 1em 0;
padding: 0;
}
span{
display: inline-block;
margin: 0;
padding: 0;
width: 200px;
vertical-align: bottom;
white-space: nowrap;
overflow: hidden;
}
--></style>
</head>
<body>
<p>This span (<span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>…) is always 200px width.</p>
</body>
</html>
This proof of concept basically does this:
- Make the span a block level element so it can be assigned a width.
- Force the span to render in one line (given that the source string does not have
<br>
tags). - Hide overflowed content.
- Fix margins and alignment so it stays at the same level than the parent element.
Improvements welcome.
Here's a function that will do that:
function display_one_line($text) {
$break = strpos($text, "\n");
if ($break === false) {
return $text;
}
return trim(substr($text, 0, $break));
}
Usage:
<span><?= display_one_line($text) ?></span>
but if you only need to do this one time, you can use this one-liner:
<span><?= (($break = strpos($text, "\n")) !== false ? substr($text, 0, $break) : $text) ?></span>
精彩评论