Css dots if it doesn't fit. Trimming single or multi-line text to height by adding an ellipsis

Home / Browsers

In some cases, the content of a block appears outside the element's boundaries, overlapping it. To control the behavior of block-level elements, use the overflow property, which determines how content that extends outside the block should be displayed.

Using the clip property, you can crop an element to specified dimensions.

1. Overflow property

The content of block elements can overflow a block when the block has an explicit height and/or width. Without specifying a height, the block will stretch to accommodate the content unless the block is positioned at position: absolute; or position: fixed; . Text can overflow the block in height, images - in height and width.

Values:
visible Default value. All content becomes visible regardless of the size of the container block. It is possible to overlap the contents of adjacent blocks.
scroll Adds scroll bars inside the element's display area that appear even when the content fits inside the block. The container dimensions do not change.
auto Adds scrollbars only when necessary.
hidden Hides content that extends beyond the boundaries of the block. May hide some content. Used for container blocks containing floating elements. Also prevents backgrounds or borders from being displayed under floated elements (that have the float: left / right; property set. This does not resize the container.
Rice. 1. Crop the block content using the overflow property Syntax: div ( width: 200px; height: 150px; overflow: hidden; )

2. Overflow-x property

The property specifies how the right edge of the content inside the block will be cut off if it overflows.

Syntax:

Div ( overflow-x: hidden; )

3. Overflow-y property

The property specifies how the bottom edge of the content inside the block will be trimmed if it overflows.

Syntax:

Div (overflow-y: hidden; )

4. Clip property

The property determines how much of the element will be visible. The part of the element that remains visible after trimming is called the clipping region. Clipping is applied to an element that is initially fully visible. The property applies to elements that have their position property set to absolute or fixed .

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 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 the same as 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" )); ( clone . text ( text . substring ( 0 , l ) + "..." ); el . text ( clone . remove ( ) ); ( return this . each (function () ( truncate ( $ ( this )); )); )( jQuery ));

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°. 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-shaped 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, straightforward 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. 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 amount entails four changes to the code.

Similarly, 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 the 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 not important for us (border-image will take care of scaling, and SVG images are perfectly scaled regardless of size - be blessed vector graphics!), all sizes 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 precision. 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. There are two ways to solve this problem: either define a background, or add the fill keyword 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 in this case this 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 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 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 pure CSS solutions presented in this book, because it requires as many as eight (!) edits to change the size of the corner.

On the other hand, the background can be changed with just one edit, so at least we have that. One of the advantages this approach- the fact that we can use absolutely any background or even crop 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 the border-radius property, which is necessary to determine the amount of cropping. For example, to describe 15px cut corners on all sides of the image, the following simple code is sufficient:

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

Also read

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

The result of this example is 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 a gradual dissolution of the text.

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. All browsers understand it, 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 ellipses

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.

© 2024 ermake.ru -- About PC repair - Information portal