Раньше я использовал инструмент с открытым исходным кодом, названный HTMLParser . Он разработан, чтобы анализировать HTML по-разному и хорошо служит цели. Он может анализировать HTML как другой treenode, и вы можете легко использовать его API для получения атрибутов из узла. Проверьте это и посмотрите, поможет ли это вам.
Чтобы скопировать текст с помощью многоточия, когда он переполняет ячейку таблицы, вам нужно будет установить свойство CSS max-width
для каждого класса td
для работы переполнения. Никаких дополнительных div div не требуется
td {
max-width: 100px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Для гибких макетов; используйте свойство CSS max-width
для определения эффективной минимальной ширины столбца или просто используйте max-width: 0;
для неограниченной гибкости. Кроме того, содержащая таблица будет иметь определенную ширину, обычно width: 100%;
, а столбцы обычно будут иметь свою ширину, заданную как процент от общей ширины
table {
width: 100%;
}
td {
max-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
td.columnA {
width: 30%;
}
td.columnB {
width: 70%;
}
Исторический: для IE 9 (или меньше) вам нужно иметь это в своем HTML, чтобы исправить IE-специфическую проблему рендеринга
<!--[if IE]>
<style>
table {
table-layout: fixed;
width: 100px;
}
</style>
<![endif]-->
Обрезать содержимое ячейки в гибком блоке.
table {
width: 100%;
}
div.parent {
display: flex;
}
div.child {
flex: 1;
width: 1px;
overflow-x: hidden;
text-overflow: ellipsis;
}
<table>
<tr>
<td>
<div class="parent">
<div class="child">
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
</div>
<div>
</td>
</tr>
</table>
white-space: nowrap;
в класс child
.
– Ross Allen
27 January 2018 в 18:09
Кажется, что если вы укажете table-layout: fixed;
на элементе table
, то ваши стили для td
должны вступить в силу. Это также повлияет на размер ячеек.
Sitepoint немного обсуждает методы табличного макета: http://reference.sitepoint.com/css/tableformatting
Нижеприведенное решение позволяет иметь содержимое ячейки таблицы, которое является длинным, но не должно влиять на ширину родительской таблицы, высота родительской строки. Например, если вы хотите иметь таблицу с width:100%
, которая по-прежнему применяет функцию автоматического размера ко всем другим ячейкам. Полезно в сетях данных с колонками «Примечания» или «Комментарий» ./
Добавьте эти 3 правила в свой CSS:
.text-overflow-dynamic-container {
position: relative;
max-width: 100%;
padding: 0 !important;
display: -webkit-flex;
display: -moz-flex;
display: flex;
vertical-align: text-bottom !important;
}
.text-overflow-dynamic-ellipsis {
position: absolute;
white-space: nowrap;
overflow-y: visible;
overflow-x: hidden;
text-overflow: ellipsis;
-ms-text-overflow: ellipsis;
-o-text-overflow: ellipsis;
max-width: 100%;
min-width: 0;
width:100%;
top: 0;
left: 0;
}
.text-overflow-dynamic-container:after,
.text-overflow-dynamic-ellipsis:after {
content: '-';
display: inline;
visibility: hidden;
width: 0;
}
Отформатируйте HTML таким образом в любой ячейке таблицы, в которой требуется динамическое переполнение текста:
<td>
<span class="text-overflow-dynamic-container">
<span class="text-overflow-dynamic-ellipsis" title="...your text again for usability...">
//...your long text here...
</span>
</span>
</td>
Дополнительно примените желаемый min-width
(или вообще ничего) к ячейке таблицы.
Конечно, скрипка: https://jsfiddle.net/9wycg99v/23/
max-width: X
, они теперь могут быть более широкими - я думал, что это из-за использования display: flex
, но я удалил это и не вижу разницы ...
– user9645
2 February 2018 в 14:21
Указание max-width
или фиксированной ширины не работает для всех ситуаций, и таблица должна быть текучей и автоматически помещать в ячейку. Для этого нужны таблицы.
Используйте это: http://jsfiddle.net/maruxa1j/
Работает на IE9 и других браузерах.
<span>
.
– Roy Tinker
2 July 2015 в 16:58
display: block
, не
– j3ff
10 April 2018 в 18:03
Почему это происходит?
Кажется, этот раздел на w3.org предполагает, что переполнение текста применяется только к элементам блока :
11.1. Overflow Ellipsis: the ‘text-overflow’ property
text-overflow clip | ellipsis | <string>
Initial: clip
APPLIES TO: BLOCK CONTAINERS <<<<
Inherited: no
Percentages: N/A
Media: visual
Computed value: as specified
Этот jsfiddle имеет ваш код (с несколько отладочных изменений), который отлично работает, если он применяется к div
вместо td
. Он также имеет единственное обходное решение, о котором я мог бы быстро подумать, путем обертывания содержимого td
в содержащем блоке div
. Однако, это выглядит как «уродливая» разметка для меня, поэтому я надеюсь, что у кого-то есть лучшее решение. Код для проверки выглядит следующим образом:
td, div {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border: 1px solid red;
width: 80px;
}
Works, but no tables anymore:
<div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div>
Works, but non-semantic markup required:
<table><tr><td><div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div></td></tr></table>
Без с использованием max-width
или процентной ширины столбцов или table-layout: fixed
и т. д.
https://jsfiddle.net/tturadqq/
Как это работает:
Шаг 1: Просто дайте автозагрузке таблицы его.
Когда есть один или несколько столбцов с большим количеством текста, он будет как можно больше сжимать другие столбцы, а затем обернуть текст длинными столбцами:
Шаг 2: Закройте содержимое ячейки в div, затем установите для этого div значение max-height: 1.1em
(дополнительный 0.1em для символов, которые [gg]
Шаг 3: Установите title
на divs
Это хорошо для доступности, и это необходимо для небольшого трюка, который мы будем использовать в одно мгновение.
Шаг 4: Добавьте CSS ::after
в div
Это сложный бит. Мы устанавливаем CSS ::after
, с content: attr(title)
, затем позиционируем это над div и устанавливаем text-overflow: ellipsis
.
(обратите внимание, как длинный столбец теперь имеет хвостовой эллипс)
< hr> Шаг 5: Установите цвет текста div на transparent
И мы закончили!
<a>
вместо <div>
внутри ячейки таблицы. Добавление word-break: break-all;
решает проблему. Пример: jsfiddle.net/de0bjmqv
– zendu
26 July 2018 в 01:25
Это версия, которая работает в IE 9.
<div style="display:table; table-layout: fixed; width:100%; " >
<div style="display:table-row;">
<div style="display:table-cell;">
<table style="width: 100%; table-layout: fixed;">
<div style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">First row. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</table>
</div>
<div style="display:table-cell;">
Top right Cell.
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<table style="width: 100%; table-layout: fixed;">
<div style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">Second row - Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
</table>
</div>
<div style="display:table-cell;">
Bottom right cell.
</div>
</div>
</div>
Когда это указано в ширине таблицы в процентах или вы не можете установить фиксированную ширину в ячейке таблицы. Вы можете применить table-layout: fixed;
, чтобы заставить его работать.
table {
table-layout: fixed;
width: 100%;
}
td {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
border: 1px solid red;
}
<table>
<tr>
<td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>
<td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>
</tr>
</table>
display: table-cell
! – OzrenTkalcecKrznaric 29 July 2013 в 14:21display: table-cell
, но не тогда, когдаmax-width
определяется в процентах (%). Проверено на FF 32 – Greg 4 September 2014 в 01:42table-layout: fixed
элемента сdisplay: table
сделает трюк – Greg 4 September 2014 в 01:53