Crop one- or multi-line text in height with the addition of ellipsis. How to cut long text with CSS dots if it doesn't fit

Problem

Cutting corners is not only fast way achieve a goal, but also a popular styling option in both print 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 began 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, this creates an arrow-shaped shape, which is also often used in the design of buttons and breadcrumb navigation elements.

However, there are still not enough tools in CSS to create this effect with simple and straightforward one-liner solutions. Because of this, many developers tend to use background images, either by covering the cut corners with triangles (on a solid color background), or by creating the entire background with 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 overall website file size.


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 gradients ability to take the direction of the angle (eg 45deg) and the position of the borders of the color transition in absolute values, which do not change when changing the overall dimensions of the element that owns the background. It follows from the above that one linear gradient will be enough for us.

We'll add a transparent color fade border to create the cut corner, and another color fade border at the same position but with the color matching the background. The CSS code would be the following (for a 15px corner):

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

Simple, right? You see the result in the figure.


Technically, we don't even need the first announcement. We've only added it as a workaround: if CSS gradients aren't supported, then the second declaration will be ignored, so we'll at least get a solid color background. Now suppose we want two cut corners, say both bottom ones. This can't be done with 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 need to make them smaller by limiting each one to half of the element with background-size :
background: #58a;

background-size: 50% 100%

You can see the result in the picture.

Even though we applied a 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 due to repetition. A new version 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! - works! You probably already guessed how to apply this effect to all four corners. You will need four gradients and code like 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's hard to maintain. It requires five edits to change the background color and four to change the angle value. A mixin created with a preprocessor could reduce the number of repetitions. Here's 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;
}


Then, when necessary, it can be called, 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 clipped by 15px and its top-right and bottom-left corners by 5px, similar to how border-radius works when we specify less than four values. This is possible because we also take care of default values ​​for arguments in our SCSS mixin - and yes, these default values ​​can refer to other arguments too.
TRY 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 gradient method allows you to create curved cut corners, an effect that many people call "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;

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

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

Solution with inline SVG and border-image

While the gradient 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 cut all four corners by the same amount, changing this amount entails four edits in the code.

Similarly, changing the background color also requires four edits, and if you include a fallback solution, then all five; animating a change in the size of a cut corner is incredibly difficult, and even impossible in some browsers. Fortunately, depending on the desired result, we can use a couple more methods. One of them involves the union 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 how the required SVG-code?

Because dimensions are not important for us (border-image takes care of scaling, and SVG images scale perfectly regardless of size - bless Vector graphics!), all sizes can be equated to one in order to operate with more convenient and short values. The cut angle value will be equal to one, and the straight sides will also be equal to one. Result (enlarged for readability). 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 . It doesn't mean 1 pixel; the actual size is determined by the coordinate system of the SVG file (that's why we don't have units). If we were using percentages, then 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 in different browsers values ​​may be rounded to varying degrees of accuracy. And by sticking to the coordinate system units of the SVG file, we save ourselves the headache that comes with all that rounding.

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

In addition, you've probably noticed that the cut corners are now smaller than with the previous technique, and this can be confusing. After all, we set the border 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 frame width is not measured diagonally, but horizontally/vertically.

Feel what I'm leading to? Yes, yes, again the ubiquitous Pythagorean theorem, which we actively used. The diagram in the figure should clarify the situation.

In short, in order to achieve the same visual result, we need a border width that is 2 times the size that 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 coveted 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? Fear not, young padawan, the corners are still there. You will immediately understand what happened if you set a different background color, for example #655.
As the figure below shows, the reason why our corners have disappeared lies in the background: the background that we defined above simply obscures them. All we need to do to fix this inconvenience is to use background-clip to prevent the background from crawling 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 resize the corners with just one edit: just adjust the border width. We can even animate this effect because border-width supports animation!

And changing the background now requires two edits instead of five. Also, since our background is independent of the corners effect, we can define a gradient or any other pattern for it, as long as the edges are still #58a .

For example, we use radial gradient from color 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 is not limited to the absence of cut corners. Because the background is clipped, the space between the edge of the field and its content will decrease. In order to fix this, we need to set the frame to the same color 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 doesn't work, the additional border color will provide a more elegant fallback solution. Its only drawback is the increase in the number of edits required to change the background color to three.
TRY YOURSELF!
http://play.csssecrets.io/bevel-corners

Clipping path solution

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

But 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 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 ​​(which we use to specify the overall dimensions of an element) with absolute values, providing incredible flexibility. For example, the code for a clipping path that clips an element to the shape of a 20px beveled rectangle (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 brief, this code snippet doesn't follow the DRY principles, and this becomes one of the biggest problems if you don't use 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 corner here you need to make as many as eight (!) edits.

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

All it takes is to use another clipping path. In addition to being verbose and having limited browser support, the downside of this solution is that if we don't take care of padding wide enough, the text will also be clipped, because when clipping an element, its constituents are not taken into account in any way. In contrast, the gradient method allows the text to simply extend beyond the cut corners (because they're just part of the background), while the border-image method works the same way as regular borders, wrapping the text on a new line.

TRY 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. New property corner shape, included in CSS Backgrounds & Borders Level 4 , will save us that headache. It will be used to create the effect of cut corners in various shapes, in combination with the border-radius property, which is needed to determine the amount of cropping. For example, to describe 15px cut corners on all sides of an image, this simple code would suffice:

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

Also read

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 text fragment should be displayed that fits completely into the specified block, after which the ellipsis is set.

Such a task is quite common, at the same time, it is not as trivial as it seems.

Variant 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 ; )

Variant for multiline text in CSS

First way to trim multiline text using CSS properties apply pseudo-elements :before And :after. Let's get started with the 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 facili si.

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 ; left : 100% ; width : 3em ; margin-left : -3em ; padding-right : 5px ; text-align : right ; background-size : 100% 100% ; background : linear-gradient (to right , rgba (255 , 255 , 255 , 0 ), white 50% , white ); )

Another way is to use the column-width property, which sets the column width for multiline text. True, when using this method, it will not work to install 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 facili si.

Block ( overflow : hidden ; height : 200px ; width : 300px ; )

The third way to solve multiline text in CSS is for browsers Webkit. In it, we will have to use several specific properties at once with the prefix -webkit. The main one is -webkit-line-clamp which allows you to specify the number of lines to display in the 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 ; )

Variant for multiline text in JavaScript

Here an additional invisible block is used, in which our text is initially placed, after which it is deleted 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" ; clone. style. width = block . clientWidth + "px" ; clone. innerHTML = text ; document. body . appendChild(clone); var l = text . length - 1 ; for (; l >= 0 && clone . clientHeight > block . clientHeight ; -- l ) ( clone . innerHTML = text . substring (0 , l ) + "..." ; ) block . innerHTML = clone . innerHTML ;

This is in the form of a plugin for jQuery:

(function ($) ( var truncate = function (el ) ( var text = el . text (), height = el . height (), clone = el . clone (); clone . css (( position : "absolute" , visibility : "hidden" , height : "auto" )); el .after (clone ); var l = text . length - 1 ; for (; l >= 0 && clone . height () > height ; -- l ) ( clone . text (text . substring (0 , l ) + "..." ); ) el . text (clone . text ()); clone . remove (); ); $ . fn . truncateText = function () ( return this . each (function () ( truncate ($ (this )); )); ); )(jQuery ));

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 need only a couple of lines css code. However, this is not circumcision in the truest sense of the word ( css can't do it yet), we just hide and show only the part of the picture we want to see.

These techniques can be very useful if you want to resize an image to a certain size, i.e. you want to create, for example, its preview (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 . The width and height define the dimensions of the displayed field. And for a picture placed inside a paragraph, the property positioning set to absolute . Then we can use properties top And left arrange the image as 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 - Use the slicing property ( Clip Property)


This technique should be the easiest, as clip property defines the part of the element to be shown. It sounds like a perfect solution, but there is one snag: clipped element must be positioned absolutely. In order to be able to use an element, we have to add an 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, isn't it?

Oh, another problem: the size of the clipped element is not reduced to the value of the crop, but remains at its original size (the picture outside the crop is simply hidden). We must use absolute positioning to move the viewport to the top left corner of the parent.

However, one cannot leave unmentioned slicing property. And so again the code...

< 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 growing, sometimes there is a task to fit a lot of text in a limited space. For example, this might 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 cut off long lines of text, leaving only the beginning of the sentence. So we will bring the interface to a compact form and reduce the amount of output information. Line cutting itself can be done on the server side using the same PHP, but it is easier through CSS, and you can always show the entire text, for example, when you hover over it with the mouse cursor. Next, consider the methods of how to cut text with imaginary scissors.

It really comes down to using the overflow property with a value of hidden . The differences only lie in the different display of our text.

Using overflow

In order for the overflow property to show itself with the text in all its glory, we need to cancel the text wrapping using white-space with a value of nowrap . If this is not done, then there will be no effect we need, hyphens will be added to the text and it will be displayed in its entirety. 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 only one drawback in general - it is not obvious that the text has a continuation, so the user must be made aware of this. For this, a gradient or ellipsis is usually used.

Adding a Gradient to Text

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

Rice. 2. Gradient Text

Example 2 shows how to create this effect. The style of the element itself will practically remain the same, but the gradient itself will be added 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 the main browsers (example 2). It is easy to change the width of the gradient through 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

The intra-discrete arpeggio transforms the polyrange, this is the one-time vertical in the ultra-polyphonic polyphonic fabric.

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

This method is only compatible with plain background and in the case of a background image, the gradient over the text will stand out.

ellipsis at the end of the text

An ellipsis can also be used instead of a gradient at the end of cropped text. 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 downside to this property is its unclear status so far. This property seems to be included in CSS3, but the code with it does not pass validation.

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

Example 3: Using text-overflow

HTML5 CSS3 IE Cr Op Sa Fx

Text

The unconscious causes contrast, this is labeled by Lee Ross as a fundamental attribution error that can be traced in many experiments.

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

Rice. 3. Text with ellipsis

The big plus of these methods is the fact that the gradient and ellipsis are not displayed if the text is short and fits entirely in the specified area. So the text will be rendered as normal when it is fully visible on the screen, and clipped when the element's width is reduced.

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

Where can it be useful?

First of all, on sites where content with images, most likely, will not be cropped to fit any particular block.

A striking example: blog on WordPress.

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

  1. Download a suitable picture 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 that you expected.

But, suppose you forgot to crop the image in Photoshop and uploaded a random image as a cover from the Internet, what will happen then?! That's right, the layout will break. And if you didn’t use CSS at all, then an HD resolution 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 with CSS, but also with SVG.

Example 1

Let's try to crop an image that is placed using background-image. Let's create some HTML markup

Let's move on to css styling. We add an image via background-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; )

This was the first and easiest method for cropping an image. Now let's look at the second example.

Example 2

Suppose we have the same box container inside which is an img tag with an image that we will now style.

We will also place our image in the center relative to the object that 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 for posts of completely different proportions.

Learn more about HTML and CSS here:

Example 3

We can also create clipping 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 wrapping svg tag inside which will be a circle tag and a pattern tag. 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 the width and height attributes. But that's not all. We will need to add a fill value. To make our work complete, we will add an auxiliary preserveAspectRatio attribute to the image tag, which will allow us to fill our image “from and to” around the circle.

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

Learn more about HTML and CSS here:

Results:
We have covered 3 methods for cropping images on websites: using background-image , using the img tag, and pattern-related svg with embedding bitmaps using the image tag. If you know any other methods for cropping an image when SVG help then share them in the comments. Not only for me, but also for others, it will be useful to learn about them.

Do not forget to ask your questions about layout or front-end development to professionals at FrontendHelp online.