Border spacing padding css

HTML Table Padding & Spacing

HTML tables can adjust the padding inside the cells, and also the space between the cells.

With Padding
hello hello hello
hello hello hello
hello hello hello
With Spacing
hello hello hello
hello hello hello
hello hello hello

HTML Table — Cell Padding

Cell padding is the space between the cell edges and the cell content.

By default the padding is set to 0.

To add padding on table cells, use the CSS padding property:

Example

To add padding only above the content, use the padding-top property.

And the others sides with the padding-bottom , padding-left , and padding-right properties:

Example

HTML Table — Cell Spacing

Cell spacing is the space between each cell.

By default the space is set to 2 pixels.

To change the space between table cells, use the CSS border-spacing property on the table element:

Example

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.

Источник

Учимся применять cellpadding и cellspacing в CSS

В HTML атрибуты cellpadding и cellspacing можно установить следующим образом:

Если нужно полностью убрать расстояние между ячейками ( установить cellspacing=»0″ ), не забудьте задать свойство border-collapse: collapse . Но как реализовать cellspacing в CSS ?

Рабочий CSS-эквивалент cellspacing – это border-spacing , но при этом он не работает в браузере Internet Explorer . Можно установить border-collapse: collapse, что также приведет к нулевым промежуткам между ячейками. Но единственным полностью кроссбраузерным решением остается применение атрибута cellspacing :

Также можно просто использовать cellpadding=»0″ cellspacing=»0″ , так как эти атрибуты еще не считаются устаревшими.

Основы

Чтобы контролировать промежутки между ячейками с помощью CSS , можно использовать отступы ( padding ), выставленные для ячеек таблицы:

Что касается эквивалентов CSS table cellspacing , то можно использовать свойство border-spacing , примененное к таблице. Например:

Данное свойство также позволит получить горизонтальные и вертикальные промежутки. То есть, реализовать то, что невозможно при помощи атрибута cellspacing .

Проблемы с IE ниже 7 версии

Эти методы будут работать практически во всех современных браузерах, за исключением Internet Explorer 7 . Все они поддерживают свойство border-collapse , которое объединяет границы смежных ячеек в таблице. Если попробовать убрать промежутки между ячейками ( cellspacing=»0″ ), то у border-collapse:collapse будет тот же эффект: отсутствие расстояния между ячейками. Стоит обратить внимание, что поддерживается этот вариант « криво », так как существующий HTML-атрибут cellspacing в CSS не переписывается.

Если вы не работаете с Internet Explorer 5-7 , используйте border-spacing . Если же вам не повезло, то используйте cellspacing:0 или border-collapse:collapse :

Если же вам не нужно нулевое значение cellspacing , то попробуйте то, что сработало у меня. Но имейте в виду, что этот вариант был протестирован только в Firefox :

Этот хак cellpadding cellspacing CSS работает в IE 6 и выше, Google Chrome , Firefox и Opera :

Объявление * предназначено для Internet Explorer 6 и 7 , а также всех остальных браузеров, которые могут проигнорировать это свойство. expression(‘separate’, cellSpacing = ’10px’) возвращает значение ‘ separate ‘, но выполняются оба состояния, так как в JavaScript можно передать больше аргументов, и все они будут использованы.

У этой проблемы есть простое решение:

Установки по умолчанию

Стандартное поведение браузера эквивалентно следующему:

Cellpadding

Позволяет задать расстояние между содержимым ячеек:

Cellspacing

cellspacing CSS отвечает за расстояние между самими ячейками:

Комбинация свойств

Комбинация свойств (дополнительно)

Примечание: если установлен атрибут border-spacing , то это указывает на то, что border collapse CSS имеет значение separate .

Можете попробовать в действии !

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

А также следующий HTML-код :

Здесь можно опробовать код в действии.

Гораздо проще создать с нужными фонами, а затем поверх этого элемента позиционировать таблицы с использованием position: absolute и background: transparent . Данный метод работает в Chrome , IE ( 6 и выше ), а также Mozilla ( 2 и выше ).

После border-collapse я использовал атрибут !important , чтобы получилось border-collapse: collapse !important . В IE 7 этот вариант отлично работал. Он переписывал исходный атрибут cellspacing .

Попробуйте следующий метод реализации CSS table cellspacing :

Для таблиц можно использовать border-collapse: collapse , а для th или td — указать padding :

Для содержимого таблицы можно применять CSS-отступы :

Это может вызвать проблемы в старых версиях Internet Explorer из-за различий в реализации блочной модели.

Ниже приведен код для сброса всех стилей cellpadding cellspacing CSS . Он находится у меня в файле reset.css :

Cellpadding используется для создания промежутков между содержимым ячеек и их границами:

Атрибут cellspacing создает пространство вокруг каждой ячейки в таблице. Чтобы добиться эффекта cellspacing в CSS , используйте свойство border-spacing :

Если свойство margin не сработало, попробуйте установить свойство display у элемента tr на block , и тогда оно точно заработает.

Стили добавляются в разметку таблиц только для того, чтобы не использовать CSS . Это может вызвать сложности, если на странице много таблиц:

В HTML5 свойства cellspacing и cellpadding для таблиц считаются устаревшими. Теперь, чтобы получить эффект cellspacing , нужно использовать border-spacing , а cellpadding компенсировать border-collapse .

И всегда старайтесь задавать значения cellpadding cellspacing CSS в стилевом файле:

cellpadding можно реализовать с помощью отступов в CSS , в то время как cellspacing можно компенсировать свойством border-spacing , примененным к таблице:

В HTML-таблице cellpadding cellspacing CSS можно установить следующим образом: чтобы получить промежутки между контентом ячеек, используйте отступы для td/th :

/******Call-Padding**********/ table < border-collapse: collapse; >td < border: 1px solid red; padding: 10px; >

Head1 Head2 Head3 Head4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44

table < border-collapse: collapse; >td

Для получения cellspacing CSS используйте свойство border-spacing для table :

/********* Cell-Spacing ********/ table < border-spacing: 10px; border-collapse: separate; >td < border: 1px solid red; >

Head1 Head2 Head3 Head4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44

/********* Cell-Spacing ********/ table < border-spacing: 10px; border-collapse: separate; >td

Источник

border-spacing

The border-spacing CSS property sets the distance between the borders of adjacent cells in a . This property applies only when border-collapse is separate .

Try it

The border-spacing value is also used along the outside edge of the table, where the distance between the table’s border and the cells in the first/last column or row is the sum of the relevant (horizontal or vertical) border-spacing and the relevant (top, right, bottom, or left) padding on the table.

Syntax

/* */ border-spacing: 2px; /* horizontal | vertical */ border-spacing: 1cm 2em; /* Global values */ border-spacing: inherit; border-spacing: initial; border-spacing: revert; border-spacing: revert-layer; border-spacing: unset; 

The border-spacing property may be specified as either one or two values.

  • When onevalue is specified, it defines both the horizontal and vertical spacings between cells.
  • When twovalues are specified, the first value defines the horizontal spacing between cells (i.e., the space between cells in adjacent columns), and the second value defines the vertical spacing between cells (i.e., the space between cells in adjacent rows).

Values

The size of the spacing as a fixed value.

Formal definition

Formal syntax

Examples

Spacing and padding table cells

This example applies a spacing of .5em vertically and 1em horizontally between a table’s cells. Note how, along its outside edges, the table’s padding values are added to its border-spacing values.

HTML

table> tr> td>1td> td>2td> td>3td> tr> tr> td>4td> td>5td> td>6td> tr> tr> td>7td> td>8td> td>9td> tr> table> 

CSS

table  border-spacing: 1em 0.5em; padding: 0 2em 1em 0; border: 1px solid orange; > td  width: 1.5em; height: 1.5em; background: #d2d2d2; text-align: center; vertical-align: middle; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to Set Cellpadding and Cellspacing in CSS

How to adjust spacing separately for the top, right, left, and bottom of each cell?

You can use the CSS padding property to adjust the spacing of each cell in an HTML table separately. The padding property takes up to four values, which correspond to the top, right, bottom, and left sides of the element, respectively.

Here’s an example of how to adjust the spacing of each cell separately in an HTML table:

html> html> head> title>Title of the document title> head> body> table> tr> td style="padding: 10px 20px 30px 40px; background-color: cyan;">Cell 1 td> td style="padding: 20px 30px; background-color: cyan;">Cell 2 td> tr> tr> td style="padding: 0 0 10px; background-color: cyan;">Cell 3 td> td style="padding: 0 20px; background-color: cyan;">Cell 4 td> tr> table> body> html>

In this example, the first cell in the first row has a padding of 10 pixels for the top, 20 pixels for the right, 30 pixels for the bottom, and 40 pixels for the left. The second cell in the first row has a padding of 20 pixels for the top and bottom, and 30 pixels for the right and left. The first cell in the second row has a padding of 0 pixels for the top and right, and 10 pixels for the bottom. The second cell in the second row has a padding of 0 pixels for the top and bottom, and 20 pixels for the right and left.

You can adjust the values of the padding property to achieve the desired spacing for each cell in the table. Additionally, you can use CSS classes to apply the same padding values to multiple cells in the table.

Источник

Читайте также:  Условные выражения си шарп
Оцените статью