Пример использования свойства CSS table-layout.

Setting table column width

How do I set the width so the From and Date are 15% of the page width and the Subject is 70%. I also want the table to take up the whole page width.

13 Answers 13

@Isu_guy you only close

when using XHTML — in HTML, tag has no closing. see link for more info. In HTML5, is a void element, meaning it MUST NOT be closed

@Zulu according to w3schools.com/tags/att_col_width.asp «The width attribute is not supported in HTML5.»

@Caltor: the code is not using the width attribute ; it is using a CSS *style* width , which is what replaced the width attribute. (despite the multiple people up-voting that comment!!)

table < width: 100%; border: 1px solid #000; >th.from, th.date < width: 15% >th.subject < width: 70%; /* Not necessary, since only 70% width remains */ >
 
From Subject Date
[from] [subject] [date]

The best practice is to keep your HTML and CSS separate for less code duplication, and for separation of concerns ( HTML for structure and semantics, and CSS for presentation).

Читайте также:  Php test smtp server

Note that, for this to work in older versions of Internet Explorer, you may have to give your table a specific width (e.g., 900px). That browser has some problems rendering an element with percentage dimensions if its wrapper doesn’t have exact dimensions.

Use the CSS below, the first declaration will ensure your table sticks to the widths you provide (you’ll need to add the classes in your HTML):

table < table-layout:fixed; >th.from, th.date < width: 15%; >th.subject

Actually you only need to specify width of the two columns. The third one will be calculated automatically, so table;.from,.date is enough. Unless the classes are used on other elements too, writing th.from is redundant and can be shortened to just .from .

Alternative way with just one class while keeping your styles in a CSS file, which even works in IE7:

 
From Subject Date
.mytable td, .mytable th < width:15%; >.mytable td + td, .mytable th + th < width:70%; >.mytable td + td + td, .mytable th + th + th

More recently, you can also use the nth-child() selector from CSS3 (IE9+), where you’d just put the nr. of the respective column into the parenthesis instead of stringing them together with the adjacent selector. Like this, for example:

 .mytable tr > *:nth-child(1) < width:15%; >.mytable tr > *:nth-child(2) < width:70%; >.mytable tr > *:nth-child(3) 

The proposed :nth-child solution is horrible in terms of performance. There is no valid reason to use it (especially with the universal selector) in this example where there are only three elements ( th or col ) to style. Additionally, you only need to set width to the th in the first row. The .mytable td in the first example is redundant.

This should be enough: Efficiently Rendering CSS. With your use of the universal selector the browser will first check ALL elements whether they are nth child of another element, then if their direct parent is tr and then whether they belong to .mytable . If you really want to use «nth» then something like this will probably be much better: .mytable th:nth-of-type(1) ; .mytable th:nth-of-type(2) ; . There is also no need to specify the third column width in this case.

Personally I would use classes or just .mytable th+th.mytable th+th+th . The «nth» selectors themselves may be very useful but in this particular case (a tiny table with only 3 columns) are not really needed. When using table-layout: fixed you can even do just this: tableth:first-child+th .

I’m aware of that. But those articles are from years back, and there are bigger problems today that CSS selectors, like huge amounts of images and JS code.

Источник

HTML Table Sizes

HTML tables can have different sizes for each column, row or the entire table.

Use the style attribute with the width or height properties to specify the size of a table, row or column.

HTML Table Width

Example

Set the width of the table to 100%:

Note: Using a percentage as the size unit for a width means how wide will this element be compared to its parent element, which in this case is the element.

HTML Table Column Width

Example

Set the width of the first column to 70%:

HTML Table Row Height

To set the height of a specific row, add the style attribute on a table row element:

Example

Set the height of the second row to 200 pixels:

HTML Exercises

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Фиксируем размер ячеек HTML таблицы с помощью CSS3

Фиксируем размер ячеек HTML таблицы с помощью CSS3

На данный ширина всех столбцов будет определяться браузером клиента автоматически, чего собственно мы и хотим избежать. Поможет нам в этом следующий CSS код:

table < table-layout:fixed; width:450px; >table td < overflow:hidden; >table td:nth-of-type(1) < width:200px; >table td:nth-of-type(2) < width:75px; >table td:nth-of-type(3)

Как можно догадаться, table td:nth-of-type(1), table td:nth-of-type(2) и table td:nth-of-type(3) содержат цифры колонок, а параметр width отвечает за их ширину. Важный совет — если у вашей таблицы задан свой определенный класс, то лучше использовать его в таблице CSS, потому что в противном случае данные размеры применятся на любые таблицы, которые расположены на страницах, где используется данный css файл. Допустим, у вашей таблицы следующий код, в котором видно, что класс таблицы — music:

 
Kraftwerk1969Германия
Deutsch Amerikanische Freundschaft1978Германия
Front 2421981Бельгия
table.music < table-layout:fixed; width:450px; >table.music td < overflow:hidden; >table.music td:nth-of-type(1) < width:200px; >table.music td:nth-of-type(2) < width:75px; >table.music td:nth-of-type(3)
table.music < table-layout:fixed; width:450px; >table.music td, table.music th < overflow:hidden; >table.music td:nth-of-type(1), table.music th:nth-of-type(1) < width:200px; >table.music td:nth-of-type(2), table.music th:nth-of-type(2) < width:75px; >table.music td:nth-of-type(3), table.music th:nth-of-type(3)

Источник

Размер ячейки html css

Если мы помним, из предыдущих тем, то ширина таблицы измеряется в

Эти свойства наследуют столбцы! Чтобы задать ширину столбца, надо знать, как устанавливать свойства css — их всего три.

Ширина столбца в процентах

Давайте поэкспериментируем! С шириной столбца в процентах!

Создадим таблицу с тремя столбцами!

И присвоим им ширину 25% + 50% + 25% сумма должна быть равна 100%.

Как видим, наша страница заполняет полное пространство на данной странице.

Результат столбца с разной шириной, в процента:

Теперь ширину столбца сделаем в пикселях.

Общая ширина текстового поля, где вы читаете данный текст не равна 600 пикселям.

Ширина столбца в пикселях

Делим на 3 части 150px + 300px + 150px

Смотрим наши получившиеся столбцы с разной шириной:

width=»150″ width=»300″ width=»150″

Ширина столбца через стили css

Теперь ширину столбца пропишем через стили css.

Сам столбец обозначается тегом «td»:

Есть несколько вариантов, как прописать ширину столбцов.

К примеру, если вы пропишите сам столбец и к нему прикрепите ширину.

Но у этого способа есть один самый главный минус — все столбцы на странице будут иметь эту ширину и если эти стили прописаны в главном файл css? то все столбцы, на всем сайте будут иметь именно эту ширину!

Поэтому, для каждого столбца нужно поставить отдельный класс или ид.

Например — таблица с шириной через css.

Обратите внимание, что на третьем столбце ширина не прописана — вопрос — какой ширины должен быть третий столбец!?

class=»first» class=»second» no class

Фиксированная ширина столбца

Как сделать ширину столбца фиксированной!?

Тут. у меня есть некое смущение! смайлы Почему!?

Давайте данный пункт разделим еще на два подпункта:

1). Теория и фиксированной ширине столбца, это свойство table-layout со значением fixed :

Специально сделал отдельный пример, где вы можете, попробовать разобраться, что к чему и есть ли какая-то разница с присутствием или отсутствием данного свойства! И подпункт 2

Код страницы с фиксированной шириной столбца:

width : 50%; /* устанавливаем ширину таблицы (без неё результат будет идентичный) */

border : 1px solid; /* устанавливаем сплошную границу 1px (по умолчанию — черная) */

table-layout : auto; /* алгоритм автоматического размещения макета таблицы браузером */

table-layout : fixed; /* алгоритм фиксированного размещения макета таблицы браузером */

table < width : 50%; >table-layout: auto;

table < width : 50%; >table-layout: fixed;

table.test3

table.test4

table.test5

Наименование Цена 45 рублей

Веревка 20 рублей Мыло жидкое

Мыло жидкое 45 рублей Мыло жидкое

table.test6

Наименование Цена 45 рублей

Веревка 20 рублей Мыло жидкое

Мыло жидкое 45 рублей Мыло жидкое

У меня . в самом начале моего пути, было несколько сайтов построенных чисто на таблицах! И приверженцем таблиц я был очень долго — столько иногда не живут.

НО! НИКОГДА, даже не слышал и не нуждался в таком свойстве, как фиксированная ширина столбца — table-layout : fixed; !

Здесь, конечно, идет речь не о самом столбце, а о таблице вообще! Но тем не менее!

Но как же я делал фиксированную ширину столбца!?

Из стилей мы видим, что первые три столбца от левого края имеют фиксированную ширину! А четвертый столбец занимает все, что осталось от 100%

Фиксированная ширина столбца через :nth-child(n)

Как можно сделать фиксированную ширину без классов, которые указаны в предыдущем пункте! Эта таблица, что приведена в качестве примера, была сделана уже довольно давно и поскольку она выполняет свою работу и классы в том чисел поддерживают фиксированную ширину. то и менять ничего не нужно!
НО СЕГОДНЯ!

Естественно я так делать не буду!

Для этого есть более цивилизованные методы установки фиксированной ширины, сегодня, только что я сделал новую таблицу(без таблиц никуда! смайлы )

Мы будем обращаться к ширине столбца по порядковому номеру столбца!

Чтобы не рассусоливать! Нам нужен первый столбец, чтобы его фиксированная ширина была 30%!

Специально не убрал два класса .table.td_child в них есть своя фишка(о которой чуть ниже)!
Если мы хотим обратиться к первому столбцу td , то пишем так : td:nth-child(1)

А фишка в чем!? Что все таблицы с классом table будут иметь свободные ширины столбцов, если это не оговорено отдельно! Вот этот класс td_child и есть отдельно. Т.е. в данном случае, первый столбец всегда будет 30%

Источник

Fixed Table Cell Width

The accepted answer does not work unless you explicitly apply a width for the desired table. Works perfectly whether you use a unit or a percentage. Figured I’d point this out since @totymedli’s answer didn’t get any votes and I didn’t want users to ignore it. However, the word-break suggestion isn’t necessary unless that’s what you’re aiming for.

What happens when you have rows with only 1 TD element that spans multiple columns? Using your sample code, if you had in a row by itself would it be 90px?

The word-break suggestion isn’t necessary, but it is useful for the rest of SO users and quite pertinent to the question, as overflowing content in fixed width tables is almost certain to ocurr in most scenarios.

Now in HTML5/CSS3 we have better solution for the problem. In my opinion this purely CSS solution is recommended:

table.fixed /*Setting the table width is important!*/ table.fixed td /*Hide text outside the cell.*/ table.fixed td:nth-of-type(1) /*Setting the width of column 1.*/ table.fixed td:nth-of-type(2) /*Setting the width of column 2.*/ table.fixed td:nth-of-type(3) /*Setting the width of column 3.*/
 
Veryverylongtext Actuallythistextismuchlongeeeeeer We should use spaces tooooooooooooo

You need to set the table’s width even in haunter’s solution. Otherwise it doesn’t work.
Also a new CSS3 feature that vsync suggested is: word-break:break-all; . This will break the words without spaces in them to multiple lines too. Just modify the code like this:

Источник

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