Text overflow ellipsis не работает flex

Flexbox и обрезание текста

Дата публикации: 2016-06-01

От автора: представим: у нас есть строка текста внутри дочернего элемента flex-контейнера. Вы хотите сделать так, чтобы текст обрезался с добавлением многоточия, а не вел себя, как блоковый элемент (или на крайний случай можно прятать выступающий текст). И вдруг все идет не по плану! Макет не работает, а родительский блок не сжимается. А ведь Flexbox должен был сделать работу с макетом проще!

К счастью есть решение (причем стандартизированное). Для этого придется воспользоваться свойствами, не относящимися к flexbox.

Что мы хотим сделать

GIF изображение показывает, как обрезается текст при уменьшении дочернего элемента.

Возможная проблема

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

GIF изображение показывает, как текст препятствует сжатию родительского блока. Контейнер не просто может не сжиматься, он может стать слишком широким.

Проблема в дочерних элементах (flex-элементах)

Странно… когда текст лежит напрямую внутри дочернего элемента, все работает нормально:

Источник

text-overflow ellipsis not working in nested flexbox

I have a two-column layout created with flexboxes.

In the right column, I have two rows, the first containing a header and the second containing the page content.

Within the header I have three columns, a button, some text, and a button.

I want the buttons to sit on the left and right of the column with the text taking up any additional room.

Finally, I want the text to have white-space:nowrap and text-overflow:ellipsis properties to truncate long titles.

My problem is this: I cannot get the text wrapping to work correctly in a flexbox that is nested in another flexbox, as shown in this fiddle:

However, the exact same code works when the header is not nested within a flex box:

Читайте также:  Как настроить прокси через роутер

How can I achieve what I want in the first fiddle?

3 Answers 3

There are two issues in your code preventing the ellipsis from working:

div.right contains div.header , which in turn contains the button and text.

div.right is a flex item in the main container ( .container ).

This means that the length of your text, which is not wrapping, will set a minimum size for parent flex items. One way to enable flex items to shrink past their content is to set a flex item to min-width: 0 .

You’ve done this already for the .content flex item, but it needs to be set on the .right item, as well.

You’ve got the .content element set to flex: 0 1 auto .

This tells the flex item to use the size of the content ( flex-basis: auto ). The text sets the size.

Instead, set the width to 0 and let the flex container distribute space, as necessary. You can do this with flex: 1 1 0 , which is the same as flex: 1 .

Источник

CSS text-overflow: ellipsis; not working?

I don’t know why this simple CSS isn’t working.

Should cut off around the 4th «Test»

17 Answers 17

text-overflow:ellipsis; only works when the following are true:

  • The element’s width must be constrained in px (pixels). Width in % (percentage) won’t work.
  • The element must have overflow:hidden and white-space:nowrap set.

The reason you’re having problems here is because the width of your a element isn’t constrained. You do have a width setting, but because the element is set to display:inline (i.e. the default) it is ignoring it, and nothing else is constraining its width either.

You can fix this by doing one of the following:

  • Set the element to display:inline-block or display:block (probably the former, but depends on your layout needs).
  • Set one of its container elements to display:block and give that element a fixed width or max-width .
  • Set the element to float:left or float:right (probably the former, but again, either should have the same effect as far as the ellipsis is concerned).
Читайте также:  Philips easylink не работает

I’d suggest display:inline-block , since this will have the minimum collateral impact on your layout; it works very much like the display:inline that it’s using currently as far as the layout is concerned, but feel free to experiment with the other points as well; I’ve tried to give as much info as possible to help you understand how these things interact together; a large part of understanding CSS is about understanding how various styles work together.

Here’s a snippet with your code, with a display:inline-block added, to show how close you were.

Источник

Flexbox and Truncated Text

Take your JavaScript to the next level at Frontend Masters.

Situation: you have a single line of text in a flex child element. You don’t want that text to wrap, you want it truncated with ellipsis (or fall back to just hiding the overflow). But the worst happens. The unthinkable! The layout breaks and forces the entire flex parent element too wide. Flexbox is supposed to be helping make layout easier!

Fortunately, there is a (standardized) solution. You just need to use a non-flexbox property/value to do it.

The potential problem

Not only might this prevent the narrowing of a container, it might blow a container out super wide.

Child elements (of the flex child) are the issue

Confusing things a bit… if the text at hand is directly within the flex child, things work fine:

The problem comes up when there are child elements, like:

The solution is min-width: 0; on the flex child

Or min-width some actual value. Without this, the flex child containing the other text elements won’t narrow past the “implied width” of those text elements.

When I first ran into this problem, I found the solution via a Pen by AJ Foster. He writes:

According to a draft spec, the above text should not fully collapse when the flex container is resized down. Because .subtitle has a width of 100%, the min-width: auto calculation that flexbox makes says that its container should be larger than we want.

I found this behavior consistent across Chrome, Opera, and Firefox. Safari was shrinking/truncating even without the min-width (against spec, I think).

  1. Works: Text is directly inside flex child
  2. Broken: Text is in an

Источник

text-overflow в сочетании с flexbox не работает [дубликат]

этот вопрос уже есть ответ здесь:

у меня есть контейнер шириной 300 пикселей с двумя изогнутыми дивами внутри.
Второй имеет ширину 100px, а другой должен занимать оставшееся пространство.
Когда я помещаю текст шире, чем оставшиеся 200px в первом div, он переполняется, и я могу использовать overflow: hidden и text-overflow: ellipsis добавить . когда текст переполняет.
Когда я ставлю h1 тег в первом div и добавить overflow и text-overflow должен создать тот же эффект.
И это (в Chrome), но в IE и Firefox div становится больше, и многоточие не работает.
Когда я удаляю дополнительный h1 layer и обновите css соответственно, описанное поведение работает так, как ожидалось.

или посмотрите на мой JSFiddle

2 ответов

вам это нужно, потому что модуль Flexbox изменил начальное значение min-width :

чтобы обеспечить более разумный минимальный размер по умолчанию для гибкий график работы пунктов, эта спецификация вводит новый авто значение в качестве начального значение мин-ширина и мин-высота свойства, определенные в В CSS 2.1.

ваша проблема здесь с содержимым div, display: block; свойство, похоже, устраняет эффект отображения flex в IE, когда я изменил его на display: flex; он работал.

кажется также, что содержимое переполняется относительно тела, которое также отображается:flex из-за flex-basis: 300px; в контейнере, и элемент h1 относительно элемента #content не переполняется, поэтому многоточие не работает.

кажется, работа над firefox версии 29.0, обратите внимание, что поведение flex полностью suuported, начиная с firefox 28+,

Источник

Оцените статью