Первый столбец таблицы из шести столбцов заполнен содержимым различной длины. Я хочу сделать его отзывчивым с помощью только одной строки, обрезанной скрытым переполнением и многоточием, при этом таблица по-прежнему реагирует в мобильном окне просмотра со 100% шириной.
Мой код:
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width=device-width, initial-scale=1">
<style>
table {
max-width: 100%;
width: 100%;
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #ddd;
}
th, td {
text-align: left;
padding: 8px;
}
td {
width: 50%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 10px;
}
tr:nth-child(even){background-color: #f2f2f2}
</style>
</head>
<body>
<h2>Responsive Table</h2>
<div style = "width: 100%;">
<table>
<tr>
<th>Content</th>
<th>Name</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
</tr>
<tr>
<td>around the table, and it will display a horizontal scroll bar when needed</td>
<td>Smith</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
</tr>
<tr>
<td>Eve Resize the browser window to see the effect. Try to remove the div element and see what happens to the table</td>
<td>Mike</td>
<td>94</td>
<td>94</td>
<td>94</td>
<td>94</td>
<td>94</td>
</tr>
<tr>
<td>Adam that is too wide, you can add a container element with overflow-x:auto around the table</td>
<td>Johnson</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
</tr>
</table>
</div>
</body>
</html>
Приведенный выше код приводит к тому, что таблица перестает реагировать и не может изменить размер первого столбца, как ожидалось.
Любая помощь высоко ценится.






Секрет кроется в display: block; многоточие применяется только к элементам уровня блока. Таким образом, вы захотите добавить следующие правила к соответствующим элементам <td>:
display: block;
width: 100px; /* However wide you want the cell to be before ellipsis */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
Это должно применяться только к первому элементу <td> в каждой строке, поэтому вы можете использовать селектор td:first-of-type.
Это можно увидеть в следующем:
table {
max-width: 100%;
width: 100%;
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #ddd;
}
th,
td {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
td:first-of-type {
display: block;
width: 100px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}<h2>Responsive Table</h2>
<div style = "width: 100%;">
<table>
<tr>
<th>Content</th>
<th>Name</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
</tr>
<tr>
<td class = "ellipsis">around the table, and it will display a horizontal scroll bar when needed</td>
<td>Smith</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
<td>50</td>
</tr>
<tr>
<td>Eve Resize the browser window to see the effect. Try to remove the div element and see what happens to the table</td>
<td>Mike</td>
<td>94</td>
<td>94</td>
<td>94</td>
<td>94</td>
<td>94</td>
</tr>
<tr>
<td>Adam that is too wide, you can add a container element with overflow-x:auto around the table</td>
<td>Johnson</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
<td>67</td>
</tr>
</table>
</div>Обратите внимание, что вы захотите использовать единицы измерения на основе пикселей, а не проценты, так как в процентах будет действовать многоточие, но сама ячейка по-прежнему будет занимать 100% ширины.
Применение приведенного ниже класса стиля к ячейке таблицы по отдельности должно привести к закреплению текста.
<style>
.clipText{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
}
.clipText:hover{
white-space: pre-wrap;
overflow: visible;
text-overflow: normal;
word-break: break-all;
}
</style>
и я бы посоветовал, если вы пытаетесь создать отзывчивую таблицу, используйте медиа-запрос css и отображайте элементы таблицы в виде блоков для маленьких экранов и располагайте их так, как вы считаете нужным, и небольшая манипуляция с js dom также может улучшить его, используя размер экрана в качестве условия .
<style type = "text/css">
@media screen and (max-width: 520px){
table, th, tr, td{
display: block;
}
table tr:first-child{
display: none;
}
table tr:nth-child(even){
background-color: royalblue;
position: relative;
margin: 2% 0%;
}
table tr:nth-child(odd){
background-color: grey;
position: relative;
margin: 2% 0%;
}
table tr:nth-child(even) td{
color: white;
font-weight: bolder;
}
table tr:nth-child(odd) td{
color: black;
font-weight: bolder;
}
table td:nth-child(1)::before{
content: "Content: ";
}
table td:nth-child(2)::before{
content: "Name: ";
}
table td:nth-child(3)::before{
content: "Points: ";
}
table td:nth-child(4)::before{
content: "Points: ";
}
table td:nth-child(5)::before{
content: "Points: ";
}
table td:nth-child(6)::before{
content: "Points: ";
}
table td:nth-child(7)::before{
content: "Points: ";
}
}
</style>
чтобы увидеть эффекты стиля выше, уменьшите / минимизируйте размер / ширину вашего браузера.
@DrunkenM оба кода работают нормально, сначала вам нужно добавить его как класс к элементу td, который вы хотите, чтобы эффект на <td class = "clipText">i am a content<td>, а для второго все, что вам нужно сделать, это уменьшить размер браузера или экрана просмотра
@DrunkenM, уменьшив размер, я имею в виду, попробуйте перетащить форму окна браузера слева направо, как будто, чтобы уменьшить его, даже работает в скрипте js, перетащите маленький экран, где таблица отображается в нижнем левом углу слева направо, вот как media queries работает :) срабатывает по размеру экрана
Наконец я понял, как решить эту проблему.
Секрет состоит в том, чтобы сделать две разные позиции в TD, которые содержат текст с многоточием. Это можно сделать, добавив новый элемент диапазона в TD с помощью позиция: абсолютная, в то время как сам TD использует позиция: относительная.
ШАГИ:
Стиль всех TD с помощью белое пространство: nowrap;
Стиль первого TD с ширина: 100% и позиция: относительная
Стилизуйте элемент диапазона в TD с помощью позиция: абсолютная;переполнение: скрыто;переполнение текста: многоточие;слева: 0;справа: 0;
Полный код моего рабочего решения:
html, body {
margin: 0;
padding: 0;
font-family: sans-serif; */
}
table {
max-width: 100%;
width: 100%;
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #ddd;
display: table;
table-layout: auto;
}
th, td {
text-align: left;
padding: 8px;
}
td {
white-space: nowrap;
margin-bottom: 10px;
}
td:nth-child(1) {
width: 100%;
position: relative;
}
td:nth-child(1):not(:empty)::after {
/* Prevent row from collapsing vertically if the first column is empty */
content: '';
display: inline-block;
}
td:nth-child(1) > span {
position: absolute;
left: 0;
right: 0;
overflow: hidden;
text-overflow: ellipsis;
}
tr:nth-child(even){background-color: #f2f2f2}<h2>Responsive Table</h2>
<div style = "width: 100%;">
<table>
<tr>
<th>Content</th>
<th>Name</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
<th>Points</th>
</tr>
<tr><td><span>overflow-x:auto around the table, and it will display a horizontal scroll bar when needed</span></td> <td><span>Smith</span></td> <td><span>50</span></td> <td><span>50</span></td> <td><span>50</span></td> <td><span>50</span></td> <td><span>50</td>
</tr>
<tr><td><span>Eve Resize the browser window to see the effect. Try to remove the div element and see what happens to the table</span></td> <td><span>Mike</span></td> <td><span><span>94</span></span></td> <td><span><span>94</span></span></td> <td><span><span>94</span></span></td> <td><span><span>94</span></span></td> <td><span><span>94</span></td>
</tr>
<tr><td><span>Adamthat is too wide, you can add a container element with overflow-x:auto around the table</span></td> <td><span>Johnson</span></td> <td><span>67</span></td> <td><span>67</span></td> <td><span>67</span></td> <td><span>67</span></td> <td><span>67</td>
</tr>
</table>
</div>
Если я установлю фиксированную ширину для первого td, td не будет реагировать в более широком окне просмотра. Я ожидаю, что первый td также сможет следить за шириной экрана.