Trimming single or multi-line text by height with the addition of an ellipsis. How to Trim Long Text Using CSS Single Line Text Solution

Problem

Cutting corners isn't just about quick way achieve the goal, but also a popular styling option as in print design, and in web design. Most often it involves cutting one or more corners of the container at an angle of 45°. IN Lately, due to the fact that skeuomorphism has begun to lose ground to flat design, this effect is especially popular. When the corners are cut on only one side and each corner takes up 50% of the element's height, it creates an arrow shape, which is also often used in the design of buttons and breadcrumb navigation elements.

However, CSS still doesn't have enough tools to create this effect with simple, clean one-liners. Because of this, many developers tend to use background images: either covering the cut corners with triangles (on a solid background), or creating the entire background using one or more images where the corners are already cut. Obviously, such methods are completely inflexible, difficult to maintain, and increase latency due to additional HTTP requests and the overall size of the website files.


An example of a website where the cut corner (bottom left of the semi-transparent Find & Book field) fits perfectly into the design

Solution

One Possible Solution offer us the almighty CSS gradients. Let's say we only want one cut corner, say the bottom right corner. The trick is to take advantage of the ability of gradients to take the direction of the angle (for example, 45deg) and the position of the color transition boundaries in absolute values, which do not change when the overall dimensions of the element to which the background belongs change. From the above it follows that one linear gradient will be enough for us.

We'll add a transparent fade border to create the cut corner, and another fade border in the same position, but with a color that matches the background. The CSS code will be as follows (for a 15px corner):

background: #58a;
background:linear-gradient(-45deg, transparent 15px, #58a 0);

Simple, isn't it? You can see the result in the figure.


Technically, we don't even need the first announcement. We only added it as a workaround: if CSS gradients are not supported, then the second declaration will be ignored, so we will at least get a solid color background. Now let's say we need two cut corners, say both bottom corners. This can't be done with just one gradient, so we'll need two. Your first thought might be something like this:

background: #58a;
background: linear-gradient(-45deg, transparent 15px, #58a 0), linear-gradient(45deg, transparent 15px, #655 0);

However, this doesn't work. By default, both gradients take up the entire area of ​​the element, so they obscure each other. We have to make them smaller by limiting each of them to half the element using background-size:
background: #58a;

background-size: 50% 100%;

You can see the result in the figure.

Even though we applied background-size , the gradients still overlap each other. The reason is that we forgot to turn off background-repeat, so each of the backgrounds is repeated twice. Consequently, one of the backgrounds still obscures the other, but this time through repetition. A new version the code looks like this:
background: #58a;
background: linear-gradient(-45deg, transparent 15px, #58a 0) right, linear-gradient(45deg, transparent 15px, #655 0) left;
background-size: 50% 100%;

You can see the result in the picture and make sure that it is finally there! - works! You've probably already guessed how to apply this effect to all four corners. You will need four gradients and code similar to the following:

background: #58a;
background: linear-gradient(135deg, transparent 15px, #58a 0) top left,

linear-gradient(-135deg, transparent 15px, #655 0) top right,

linear-gradient(-45deg, transparent 15px, #58a 0) bottom right,

linear-gradient(45deg, transparent 15px, #655 0) bottom left;
background-size: 50% 50%;
background-repeat: no-repeat;

ADVICE
We used different colors (#58a and #655) to make debugging easier. In practice, both gradients will be the same color.
But the problem with the previous code is that it is difficult to maintain. It requires five edits to change the background color and four to change the angle value. A mixin created using a preprocessor could reduce the number of repetitions. This is what this code would look like in SCSS:
SCSS
@mixin beveled-corners($bg,
$tl:0, $tr:$tl, $br:$tl, $bl:$tr) (
background: $bg;
background:
linear-gradient(135deg, transparent $tl, $bg 0)
top left,
linear-gradient(225deg, transparent $tr, $bg 0)
top right,
linear-gradient(-45deg, transparent $br, $bg 0)
bottom right,
linear-gradient(45deg, transparent $bl, $bg 0)
bottom left;
background-size: 50% 50%;
background-repeat: no-repeat;
}


It can then be called when needed, as shown below, with 2-5 arguments:
SCSS
@include beveled-corners(#58a, 15px, 5px);
In this example, we'll end up with an element that has its top-left and bottom-right corners trimmed by 15px and its top-right and bottom-left corners trimmed by 5px, similar to how border-radius works when we specify less than four values. This is possible because we also took care of default values ​​for the arguments in our SCSS mixin - and yes, those default values ​​can refer to other arguments too.
TRY IT YOURSELF!
http://play.csssecrets.io/bevel-corners-gradients

Curved cut corners


An excellent example of using curved cut corners on a website. http://g2geogeske.com the designer has made them a central design element: they are present in the navigation, in the content, and even in the footer.
A variation of the method with gradients allows you to create curved cut corners - an effect that many call the "inner border radius" because it looks like an inverted version of rounded corners. The only difference is the use of radial gradients instead of linear ones:
background: #58a;
background: radial-gradient(circle at top left, transparent 15px, #58a 0) top left,

radial-gradient(circle at top right, transparent 15px, #58a 0) top right,

radial-gradient(circle at bottom right, transparent 15px, #58a 0) bottom right,

radial-gradient(circle at bottom left, transparent 15px, #58a 0) bottom left;
background-size: 50% 50%;
background-repeat: no-repeat;

As in the previous technique, the size of the angle can be controlled by the positions of the color transition boundaries, and a mixin can make this code more suitable for further maintenance.

TRY IT YOURSELF!
http://play.csssecrets.io/scoop-corners

Solution with string SVG and border-image

While the gradients-based solution works, it has a few drawbacks:
The code is very long and full of repetition. In the most common case, when we need to trim all four corners by the same amount, changing this value entails four changes to the code.

Likewise, changing the background color also requires four edits, and if you take into account the fallback solution, then all five; Animating changes in the size of a cut corner is incredibly difficult, and in some browsers it is completely impossible. Fortunately, depending on desired result we can use a couple more methods. One of them involves unification border-image with a string SVG code in which the corners are generated.

Knowing how it works border-image(if you need to refresh this knowledge in your memory, you will find a hint), can you already imagine what the required one should look like? SVG-code?

Since overall dimensions are unimportant for us (border-image takes care of scaling, and SVG images scale perfectly regardless of size - vector graphics be blessed!), all dimensions can be equated to one in order to operate with more convenient and shorter values. The value of the cut corner will be equal to one, and the straight sides will also be equal to one. Result (enlarged for easier viewing). The code required for this is shown below:
border: 15px solid transparent;


width=”3″ height=”3″ fill=”%2358a”>\
\
’);


Note that the slicing step size is 1. This doesn't mean 1 pixel; the actual size is determined by the SVG file's coordinate system (which is why we don't have units). If we used percentages, we would have to approximate 1/3 of the image with a fractional value, like 33.34% . It is always risky to resort to approximate values, since different browsers Values ​​may be rounded to varying degrees of accuracy. And by sticking to the units of change in the SVG file's coordinate system, we save ourselves the headache that comes with all that rounding.

As you can see, the cut corners are present, but there is no background. This problem can be solved in two ways: either define a background, or add keyword fill to the border-image declaration so that the center slice element is not discarded. In our example, we'd rather define a separate background, since this definition will also serve as a workaround for browsers that don't support this solution.

Additionally, you've probably noticed that the corners cut are now smaller than with the previous technique, which can be confusing. We set the frame width to 15px! The reason is that in the gradient solution, these 15 pixels were measured along the gradient line, which is perpendicular to the direction of the gradient. However, the width of the frame is measured not diagonally, but horizontally/vertically.

Do you feel where I'm going with this? Yes, yes, again the ubiquitous Pythagorean theorem, which we actively used. The diagram in the figure should make things clearer.

In short, in order to achieve the same visual result, we need a border width that is 2 times the size we would use in the gradient method. In this case, it will be a pixel, which is most reasonable to approximate to 20px, unless we are faced with the task of bringing the diagonal size as close as possible to the cherished 15px:

border-image: 1 url(‘data:image/svg+xml,\

width=”3″ height=”3″ fill=”%2358a”>\

0.2″/>\
’);
background: #58a;
However, as you can see, the result is not quite what we expected.

Where did our painstakingly cut corners go? Don't be afraid, young Padawan, the corners are still in place. You'll immediately understand what happened if you set a different background color, like #655.
As the image below demonstrates, the reason why our corners disappeared is because of the background: the background we defined above is simply obscuring them. All we need to do to eliminate this inconvenience is to use background-clip to prevent the background from creeping under the frame area:
border: 20px solid transparent;
border-image: 1 url(‘data:image/svg+xml,\

width=”3″ height=”3″ fill=”%2358a”>\

0.2″/>\
’);
background: #58a;


Now the problem is solved and our field looks exactly the same as before. Plus, this time we can easily change the size of the corners with just one edit: simply adjust the width of the frame. We can even animate this effect because border-width supports animation!

And changing the background now requires two edits instead of five. Additionally, since our background doesn't depend on the effect applied to the corners, we can give it a gradient or any other pattern, as long as the color at the edges is still #58a .

For example, we use a radial gradient from hsla(0,0%,100%,.2) to transparent. There is only one small problem left to solve. If border-image is not supported, then the fallback solution will not be limited to the absence of cut corners. Because the background is cropped, there will be less space between the edge of the field and its contents. In order to fix this, we need to define the same color for the frame that we use for the background:
border: 20px solid #58a;
border-image: 1 url(‘data:image/svg+xml,\

width=”3″ height=”3″ fill=”%2358a”>\
\
’);
background: #58a;
background-clip: padding-box;

In browsers where our definition border-image is supported, this color will be ignored, but where border-image fails, an additional border color will provide a more elegant fallback solution. Its only drawback is that it increases the number of edits required to change the background color to three.
TRY IT YOURSELF!
http://play.csssecrets.io/bevel-corners

Clipping Path Solution

Although the border-image solution is very compact and follows the DRY principles well, it does impose certain limitations. For example, our background should still be filled either entirely or at least along the edges with a solid color.

What if we want to use a different type of background, such as a texture, pattern, or linear gradient? There is another method that does not have such restrictions, although, of course, there are certain restrictions on its use.

Remember the property clip-path from the secret “How to make a rhombus”? CSS clipping paths have an amazing property: they allow you to mix percentage values ​​(the way we specify the overall dimensions of an element) with absolute values, providing incredible flexibility. For example, the code for a clipping path that crops an element to a 20px rectangle with beveled corners (measured horizontally) looks like this:
background: #58a;
clip-path: polygon(
20px 0, calc(100% - 20px) 0, 100% 20px,
100% calc(100% - 20px), calc(100% - 20px) 100%,
20px 100%, 0 calc(100% - 20px), 0 20px);
Although short, this piece of code does not follow DRY principles, and this becomes one of the biggest problems if you are not using a preprocessor. In fact, this code is the best illustration of the WET principle of all the solutions on pure CSS presented in this book, because to change the size of the angle, you need to make as many as eight (!) edits.

On the other hand, the background can be changed with just one edit, so at least we have that. One of the advantages of this approach is that we can use absolutely any background or even crop out substitute elements such as images. The illustration shows an image stylized using cut corners. None of the previous methods can achieve this effect. In addition, the clip-path property supports animation, and we can animate not only the change in the size of a corner, but also the transitions between different shapes.

All you need to do is use a different clipping path. Aside from being verbose and having limited browser support, the downside to this solution is that if we don't make sure the padding is wide enough, the text will also be cut off, since cropping the element doesn't take any of its components into account. In contrast, the gradient method allows the text to simply extend beyond the cut corners (after all, they are just part of the background), and the border-image method works the same way as regular borders - it wraps the text on a new line.

TRY IT YOURSELF!
http://play.csssecrets.io/bevel-corners-clipped

FUTURE CUT CORNERS
In the future, we won't have to resort to CSS gradients, clipping, or SVG to achieve the effect of cut corners. New property corner-shape, included in CSS Backgrounds & Borders Level 4 , will save us from this headache. It will be used to create the effect of corners cut into different shapes in combination with border-radius property, which is necessary to determine the amount of trimming. For example, to describe 15px cut corners on all sides of an image, the following simple code is sufficient:

border-radius: 15px;
corner-shape: bevel;

Also read

Hello everyone, my name is Anna Blok and today we will talk about how to crop images without using graphics programs.

Where can this be useful?

First of all, on sites where content with images most likely will not be cropped for any specific block.

A striking example: blog on WordPress.

Let's say you want the cover of your article to have a 1:1 (square) aspect ratio. Your actions:

  1. Download a suitable image from the Internet;
  2. Crop it in Photoshop to the desired proportions;
  3. Publish an article.

When you visit the site, you will see the result you expected.

But, suppose you forgot to crop the image in Photoshop and downloaded a random image as a cover from the Internet, what will happen then?! That's right, the layout will break. And if you haven’t used CSS at all, then an HD image can completely block the entire view of the text. Therefore, it is important to be able to crop images when CSS help styles.

Let's look at different situations of how this can be implemented not only using CSS, but also SVG.

Example 1

Let's try to crop the image that is placed using background-image. Let's create a little HTML markup

Let's move on to CSS styling. Using background-image we add an image, specify the frames for our image, center the image using background-position and set the background-size:

jpg);

background-position:center center;

background-size:cover;

width:300px;

height:300px; )

Box ( position: relative; overflow:hidden; width:300px; height:300px; ) .box img ( position: absolute; top:50%; left:50%; transform:translate(-50%,-50%); width:300px; height:300px; object-fit:cover)

In my opinion this is best method. It is ideal for blogs if you use images of completely different proportions for posts.

You can learn more about HTML and CSS here:

Example 3

We can also create cropping for images at the moment if we insert them into SVG elements. Let's take a circle as an example. We can create SVG using tags. Create a svg border tag that will contain a circle tag and a pattern tag inside. In the pattern tag we write the image tag. In it we specify the xlink:href attribute and add an image. We will also add width and height attributes. But that's not all. We will need to add the fill value. For our work to be considered complete, we will add the preserveAspectRatio auxiliary attribute to the image tag, which will allow us to fill our image “from start to finish” around the entire circle.

I cannot call this method universal. But it can be used in exceptional cases. For example, if we touched on the topic of a blog, then this method could ideally fit into the avatar of the author who writes the article.

You can learn more about HTML and CSS here:

Results:
We looked at 3 methods of cropping images on websites: using background-image , using the img tag and associated with the svg pattern with embedding raster images using the image tag. If you know any other methods for cropping an image using SVG, then share them in the comments. It will be useful not only for me, but also for others to know about them.

Don’t forget to ask your questions about layout or front-end development from professionals at FrontendHelp online.

In this article we will tell you about 3 fast and simple methods CSS, which you can use to show only part of the image on your page.

All the methods used here actually only require a couple of lines CSS code. However, this is not circumcision in the truest sense of the word ( CSS cannot do this yet), we simply hide and show only that part of the picture that we want to see.

These techniques can be very useful if you want to bring an image to a certain size, that is, you want to create, for example, a preview of it (a smaller copy of the image) in the news section or something similar.

Technique 1 - Using Negative Margins ( Negative Margins)

If you don't feel like using negative margins, we suggest using the technique №2 . It includes a parent (paragraph) that has a specific width and height. This paragraph has the property positioning set to relative . Width and height define the dimensions of the displayed field. And a picture placed inside a paragraph has the property positioning set to absolute . Then we can use properties top And left arrange the picture however we want, in the process determining which part of the image to show and which not.

HTML identical to the code from the previous technique:

< p class = "crop" > < a href = "#" title = "" > < img src = "img.jpg" alt = "" / > < / a > < / p >

Crop (

float: left;

margin: . 5em 10px . 5em 0 ;

overflow: hidden; /* this is important */

position: relative; /* this is important too */

border : 1px solid #ccc;

width: 200px;

height: 120px;

Crop img (

position: absolute;

top : - 40px ;

left : - 50px ;

Technique 3 - Using the Slicing Property ( Clip Property)


This technique should be the easiest, since clip property defines the part of the element that should be shown. This sounds like a perfect solution, but there is one catch: clipped element must be positioned absolutely. To be able to use the element, we will have to add additional element, calculate the size of the visible area of ​​the image, add this size to the parent, use the parent... A lot of work, right?

Oh, one more problem: the size of the cropped element is not reduced to the crop size, but remains the original size (the picture outside the crop is simply hidden). We must use absolute positioning to move the visible area to the top left corner of the parent.

However, it cannot be left unmentioned slicing property. And so the code again...

< div class = "crop" > < a href = "#" title = "" > < img src = "img.jpg" alt = "css template" / > < / a > < / div >

Vlad Merzhevich

Despite the fact that large diagonal monitors are becoming more affordable and their resolution is constantly increasing, sometimes the task arises of fitting a lot of text in a limited space. For example, this may be needed for mobile version site or for an interface in which the number of lines is important. In such cases, it makes sense to trim long lines of text, leaving only the beginning of the sentence. This way we will bring the interface to a compact form and reduce the amount of information displayed. The line trimming itself can be done on the server side using the same PHP, but it’s easier through CSS, and you can always show the entire text, for example, when you hover the mouse cursor over it. Next, we’ll look at methods for cutting text with imaginary scissors.

In reality, it all comes down to using the overflow property with the value hidden . The differences only lie in the different display of our text.

Using overflow

In order for the overflow property to show itself with text in all its glory, you need to unwrap the text using white-space with the value nowrap . If this is not done, then the effect we need will not occur; hyphens will be added to the text and the entire text will be displayed. Example 1 shows how to trim long text with a specified set of style properties.

Example 1. overflow for text

HTML5 CSS3 IE Cr Op Sa Fx

Text

Result this example shown in Fig. 1.

Rice. 1. The appearance of the text after applying the overflow property

As can be seen from the figure, there is generally one drawback - it is not obvious that the text has a continuation, so the user must be made aware of this. This is usually done using a gradient or ellipsis.

Adding a Gradient to Text

To make it clearer that the text on the right does not end, you can overlay a gradient from a transparent color to the background color on top of it (Fig. 2). This will create the effect of the text gradually dissolving.

Rice. 2. Gradient text

Example 2 shows how to create this effect. The style of the element itself will remain practically the same, but we will add the gradient itself using the ::after pseudo-element and CSS3. To do this, we insert an empty pseudo-element through the content property and apply a gradient to it with different prefixes for major browsers (example 2). The width of the gradient can be easily changed using width , you can also adjust the degree of transparency by replacing the value 0.2 with your own.

Example 2: Gradient over text

HTML5 CSS3 IE 8 IE 9+ Cr Op Sa Fx

Text

An intra-discrete arpeggio transforms a polyseries; this is a one-time vertical in a super polyphonic fabric.

This method does not work in Internet browser Explorer up to version 8.0 inclusive, because it does not support gradients. But you can abandon CSS3 and make a gradient the old fashioned way, through an image in PNG-24 format.

This method can only be combined with a plain background, and in the case of a background image, the gradient on top of the text will be noticeable.

Ellipsis at the end of the text

You can also use an ellipsis at the end of cropped text instead of a gradient. Moreover, it will be added automatically using the text-overflow property. It is understood by all browsers, including older versions of IE, and the only drawback of this property is that its status is currently unclear. CSS3 seems to include this property, but the code with it does not pass validation.

Example 3 shows the use of the text-overflow property with the value ellipsis, which adds an ellipsis. When you hover your mouse over the text, it is displayed in its entirety and highlighted in a background color.

Example 3: Using text-overflow

HTML5 CSS3 IE Cr Op Sa Fx

Text

The unconscious causes a contrast, this is designated by Lee Ross as the fundamental attribution error, which can be seen in many experiments.

The result of this example is shown in Fig. 3.

Rice. 3. Text with ellipsis

The big advantage of these methods is that the gradient and ellipses are not displayed if the text is short and fits entirely into a given area. So the text will be displayed as usual when it is completely visible on the screen and will be cut off when the width of the element is reduced.

There is text of arbitrary length that needs to be displayed inside a block of fixed height and width. In this case, if the text does not fit completely, a fragment of text that completely fits into the given block should be displayed, after which an ellipsis is set.

This task is quite common, but at the same time it is not as trivial as it seems.

Option for single line text in CSS

In this case, you can use the text-overflow: ellipsis property. In this case, the container must have the property overflow equal hidden or clip

Block ( width : 250px ; white-space : nowrap ; overflow : hidden ; text-overflow : ellipsis ; )

Option for multiline text in CSS

The first way to trim multiline text is using CSS properties apply pseudo elements :before And :after. Let's get started with HTML markup

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

And now the properties themselves

Box ( overflow : hidden ; height : 200px ; width : 300px ; line-height : 25px ; ) .box :before ( content : "" ; float : left ; width : 5px ; height : 200px ; ) .box > * :first -child ( float : right ; width : 100% ; margin-left : -5px ; ) .box :after ( content : "\02026" ; box-sizing : content-box ; float : right ; position : relative ; top : -25px ; width : 3em ; padding-right : 5px ; background-size : 100% 100% ; (255, 255, 255, 0), white 50%, white);

Another way is to use the column-width property, with which we set the column width for multiline text. However, when using this method, it will not be possible to set an ellipsis at the end. HTML:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

Block ( overflow : hidden ; height : 200px ; width : 300px ; ) .block__inner ( -webkit-column-width : 150px ; -moz-column-width : 150px ; column-width : 150px ; height : 100% ; )

There is a third way to solve multiline text using CSS for browsers Webkit. In it we will have to use several specific properties with the prefix -webkit. The main one is -webkit-line-clamp which allows you to specify the number of lines to be output in a block. The solution is beautiful but rather limited due to its work in a limited group of browsers

Block ( overflow : hidden ; text-overflow : ellipsis ; display : -webkit-box ; -webkit-line-clamp : 2 ; -webkit-box-orient : vertical ; )

Option for multiline text in JavaScript

Here an additional invisible block is used, in which our text is initially placed, after which it is removed one character at a time until the height of this block becomes less than or equal to the height of the desired block. And at the end the text is moved to the original block.

var block = document. querySelector(".block"), text = block. innerHTML, clone = document. createElement("div");

clone style. position = "absolute" ;

clone style. visibility = "hidden" ;


(function ($ ) ( var truncate = function (el ) ( var text = el . text (), height = el . height (), clone = el . clone (); clone . css (( position : "absolute" , visibility : "hidden" , height : "auto" )); ( clone . text ( text . substring ( 0 , l ) + "..." ); el . text ( clone . remove ( ) ); ( return this . each (function () ( truncate ( $ ( this )); )); )( jQuery ));