Cellpadding for table css

CSS Cellpadding

You may be familiar with the HTML ‘cellpadding’ attribute of the ‘table’ tag. This attribute creates space inside of a table cell so that you get a nice bit of white space, or «padding», between your element and the sides of the table.

Well, there isn’t actually a CSS ‘cellpadding’ property or attribute, but there is the CSS padding property which allows you to achieve the same effect — and more. You can use this property to set the padding on your table cells. You can even set different padding for each side of the cell. Furthermore, you can use this property on most elements — you’re not limited to table cells.

HTML ‘cellpadding’ Example

Here’s a typical example of cellpadding usage in HTML.

CSS ‘padding’ Example

To achieve the same effect using CSS, use the following code.

Padding for Each Side

One of the great things about the CSS ‘padding’ property is that you can apply different padding to each side of the cell.

There are two methods of specifying padding for different sides of an element.

Method 1

This method sets padding using the padding-top, padding-right, padding-bottom, and padding-left properties.

Method 2

This method uses a shorthand property for setting padding-top, padding-right, padding-bottom, and padding-left. This method is quicker. It also uses less code than the previous method. Actually, it’s the same property that we used in our first example.

Here, we apply multiple values against the padding property.

Variations

You don’t need to provide different values for all four sides. You can provide one, two, three, or four values. Here’s how it works:

If there is only one value, it applies to all sides. If there are two values, the top and bottom paddings are set to the first value and the right and left paddings are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively.

  • All four sides have padding of 10 pixels.
  • Top and bottom have padding of 10 pixels.
  • Right and left have padding of 20 pixels.
  • Top is 10px
  • Left and right are 20px
  • Bottom is 30px
  • Top is 10px
  • Right is 20px
  • Bottom is 30px
  • Left is 40px

Padding on Other Elements

As mentioned, you can apply padding to most HTML elements — not just table cells.

Читайте также:  Таблицы

In this case, instead of applying padding against a table cell, we apply it to a div element.

Also, this example uses inline style sheets to apply the padding (the previous example uses embedded style sheets).

As you can see, applying padding to an element can affect the size of that element. In the example above, both div elements are specified to be 100 pixels wide. However, the padding on the first div pushes the size out, resulting in a larger div .

Further Information

You can’t apply CSS padding to table-row-group, table-header-group, table-footer-group, table-row, table-column-group and table-column elements.

You can also use CSS border-collapse to collapse the border. Although this can have a similar effect to cellpadding in some cases, it isn’t padding and shouldn’t really be used as such.

Источник

Учимся применять 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 .

Читайте также:  No expression found python

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

Оберните содержимое ячейки в 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

Источник

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.

Читайте также:  Php строки найти символы

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.

Источник

Set cellpadding and cellspacing in CSS?

Just a general suggestion, check to see if your style.css does a «reset» on your tables before trying these solutions. Example: If you don’t have tables set to width:auto then border-collapse might not work as expected.

«Oh, dang, back in the olden days I did this with cellpadding and cellspacing . what is that in CSS again?» –me, pretty much every time I need to do this.

19 Answers 19

For controlling «cellpadding» in CSS, you can simply use padding on table cells. E.g. for 10px of «cellpadding»:

For «cellspacing», you can apply the border-spacing CSS property to your table. E.g. for 10px of «cellspacing»:

This property will even allow separate horizontal and vertical spacing, something you couldn’t do with old-school «cellspacing».

Issues in IE ≤ 7

This will work in almost all popular browsers except for Internet Explorer up through Internet Explorer 7, where you’re almost out of luck. I say «almost» because these browsers still support the border-collapse property, which merges the borders of adjoining table cells. If you’re trying to eliminate cellspacing (that is, cellspacing=»0″ ) then border-collapse:collapse should have the same effect: no space between table cells. This support is buggy, though, as it does not override an existing cellspacing HTML attribute on the table element.

In short: for non-Internet Explorer 5-7 browsers, border-spacing handles you. For Internet Explorer, if your situation is just right (you want 0 cellspacing and your table doesn’t have it defined already), you can use border-collapse:collapse .

Note: For a great overview of CSS properties that one can apply to tables and for which browsers, see this fantastic Quirksmode page.

Источник

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