Trimming single or multi-line text by height with the addition of an ellipsis. How to trim a long line by the number of characters css and js solution to the problem Solution for multi-line text

Adding an ellipsis at the end of the text can be achieved in several ways, at our disposal css and js.

First, let's look at the problem. There is block marking



  • A lot of interesting text about styles, layout, programming and many more interesting things about websites

  • But how can we put an ellipsis if we cannot limit the block size?

  • How about a js script? He can do this, right?

  • Hmm, it definitely can. Here, keep the code, it will count Unicode characters and trim if necessary


Now you need to achieve the effect of cutting off the text in each list element, in addition to this you need to add an ellipsis.

Trimming css text

To do this, let's create a style for the tit class
.tit(
white-space: nowrap; /* Cancel text wrapping */
overflow: hidden; /* Trim the contents */
padding: 5px; /* Fields */
text-overflow: ellipsis; /* Ellipsis */
}

The peculiarity of this solution is that if the text fits within the block size, then the ellipsis will not be added. Which is not always the solution to the problem.

Most often, you need to trim the text to its length and only then add points.
There are also tasks when it is necessary to add periods in any case (no matter how long the text is, at least 3 letters). And if the text is longer than a certain size, then it needs to be trimmed. In this case, it is necessary to use scripts.

We cut the text according to the number of characters and add an ellipsis regardless of the length


function title() (
var elem, size, text;
var elem = document.getElementsByClassName("tit");
var text = elem.innerHTML;
var size = 75;
var n = 70;
for(var i = 0; i< elem.length; i++) { /* необходимо вставить цикл, чтоб получить все блоки с классом tit */
if(elem[i].innerHTML.length > size) (
text = elem[i].innerHTML.substr(0,n);
}
else(
text = elem[i].innerHTML;
}
elem[i].innerHTML = text + "...";
}
}
title();

What are we doing?

We tell the script which elements need to be processed.
To do this, in the line var elem = document.getElementsByClassName("tit"); indicate the class of the element (it must be the same).

You then need to set the size of the text before cutting it. These are our short lines to which an ellipsis will be added. The variable var size = 75 is responsible for this;

Now the script should go through all elements with the required class and add an ellipsis.
The script checks the length of each line and truncates the text if it exceeds 75 characters. If the length is less, then an ellipsis is simply added (line if(elem[i].innerHTML.length > size)).

You can see the script in action on the demo page. That's all, now you know how to trim long text various methods.

We always want everything on the site to be neat, but for example, you have blocks with text that need to fit within certain boundaries, this could be an announcement for an article or a description of a product. At the same time, we have the text arbitrary length. Of course, you can constantly adjust the text to the size of the field so that nothing goes wrong, or you can make it so that the extra text is hidden.

There is a simple CSS solution for this. Using the property text-overflow: ellipsis, which allows you to trim a line with a long test. In order to this decision worked, you need to specify the width of the parent block, and have the property overflow equal hidden or clip.

Single line text solution:

Box-text ( text-overflow: ellipsis; //image of long blocks with text overflow: hidden; //hide overflowing text width: 100%; //width of the block with text white-space: nowrap; //prohibition of wrapping text)

All their equipment and tools were alive, in one form or another.

All their equipment and tools were alive, in one form or another.

Solution for multiline text:

But to trim multi-line text in CSS you will have to resort to pseudo-elements :before And :after.

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

The left side of the forest was dark, in shadow; the right one, wet, glossy, glistened in the sun, slightly swaying in the wind. Everything was in bloom; the nightingales chattered and rolled, now close, now far away.

The left side of the forest was dark, in shadow; the right one, wet, glossy, glistened in the sun, slightly swaying in the wind. Everything was in bloom; the nightingales chattered and rolled, now close, now far away.

Problem

Cutting corners isn't just about quick way achieve the goal, but also a popular styling option in both print design and web design. Most often it involves cutting one or more corners of the container at an angle of 45°. Recently, due to the fact that skeuomorphism has begun to lose ground 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 cover the cut corners with triangles (on a single-color background), or create 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 the use of curved cut corners on the website http://g2geogeske.com, the designer 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 the 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 consider backup 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 the desired result, we can use a couple more methods. One of them involves combining border-image with string SVG code, in which the corners are generated.

Knowing how border-image works (if you need a refresher, there's a hint here), can you already imagine what the required SVG code should look like?

Since overall dimensions are not important for us (border-image will take care of scaling, and SVG images are perfectly scaled regardless of dimensions - be blessed Vector graphics!), all sizes can be equated to unity 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;

\
\
’);


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,\
\
\
’);
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,\
\
\
’);
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,\
\
\
’);
background: #58a;
background-clip: padding-box;

In browsers where our border-image definition is supported, this color will be ignored, but where border-image doesn't work, 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 DRY principles well, it does impose certain limitations. For example, our background should still be either entirely, or at least along the edges, filled 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 clip-path property from the secret “How to make a diamond”? CSS clipping paths have an amazing property: they allow you to blend percentage values(with the help of which we indicate the overall dimensions of an element) with absolute ones, 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, in order to realize the effect of cut corners, we will not have to resort to CSS gradients, clipping or SVG. The new corner-shape property, 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 the border-radius property, which is necessary to determine the amount of cropping. 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: a blog on WordPress.

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

  • Download a suitable image from the Internet;
  • Crop it in Photoshop to the desired proportions;
  • 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 know how to crop images using CSS 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;

    We will also center our image relative to the object we will create. And we use a property that is quite rarely used: object-fit .

    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 the 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 on FrontendHelp online.