Как сделать расстояние между ячейками в html
Перейти к содержимому

Как сделать расстояние между ячейками в html

  • автор:

border-spacing

The border-spacing CSS property sets the distance between the borders of adjacent cells in a <table> . 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.

Note: The border-spacing property is equivalent to the deprecated cellspacing attribute of the <table> element, except that border-spacing has an optional second value that can be used to set different horizontal and vertical spacing.

Syntax

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

  • When one <length> value is specified, it defines both the horizontal and vertical spacings between cells.
  • When two <length> values 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

Initial value 0
Applies to table and inline-table elements
Inherited yes
Computed value two absolute lengths
Animation type discrete

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.

Space between two rows in a table?

johannchopin's user avatar

You need to use padding on your td elements. Something like this should do the trick. You can, of course, get the same result using a top padding instead of a bottom padding.

In the CSS code below, the greater-than sign means that the padding is only applied to td elements that are direct children to tr elements with the class spaceUnder . This will make it possible to use nested tables. (Cell C and D in the example code.) I’m not too sure about browser support for the direct child selector (think IE 6), but it shouldn’t break the code in any modern browsers.

This should render somewhat like this:

In the parent table, try setting

Plus a border declaration, and see if this achieves your desired effect. Beware, though, that IE doesn’t support the "separated borders" model.

You have table with id albums with any data. I have omitted the trs and tds

since I have a background image behind the table, faking it with white padding wouldn’t work. I opted to put an empty row in-between each row of content:

then use css to give the spacer rows a certain height and transparent background.

The border-spacing CSS property specifies the distance between the borders of adjacent cells (only for the separated borders model). This is equivalent to the cellspacing attribute in presentational HTML, but an optional second value can be used to set different horizontal and vertical spacing.

That last part is often overseen. Example:

UPDATE

I now understand that the OP wants specific, seperate rows to have increased spacing. I’ve added a setup with tbody elements that accomplishes that without ruining the semantics. However, I’m not sure if it is supported on all browsers. I made it in Chrome.

The example below is for showing how you can make it look like the table exists of seperate rows, full blown css sweetness. Also gave the first row more spacing with the tbody setup. Feel free to use!

Support notice: IE8+, Chrome, Firefox, Safari, Opera 4+

You may try to add separator row:

You can’t change the margin of a table cell. But you CAN change the padding. Change the padding of the TD, which will make the cell larger and push the text away from the side with the increased padding. If you have border lines, however, it still won’t be exactly what you want.

Take a look at the border-collapse: separate attribute (default) and the border-spacing property.

First, you have to seperate them with border-collapse, then you can define the space between columns and rows with border-spacing .

Both of these CSS properties are actually well-supported on every browser, see here.

Make sure the background color is set on the td rather than the row. This should work across most browsers. (Chrome, ie & ff tested)

You need to set border-collapse: separate; on the table; most browser default stylesheets start at border-collapse: collapse; , which ditches border spacing.

Also, border-spacing: goes on the TD , not the TR .

David Silva-Barrera's user avatar

You can use line-height in the table:

alansiqueira27's user avatar

A too late answer 🙂

If you apply float to tr elements, you can space between two rows with margin attribute.

For creating an illusion of spacing between rows, apply background color to row and then create a thick border with white color so that a «space» is created 🙂

Varun Natraaj's user avatar

I stumbled upon this while struggling with a similar issue. I’ve found Varun Natraaj’s answer to be quite helpful, but I would use a transparent border instead.

Transparent borders still have width.

The correct way to give spacing for tables is to use cellpadding and cellspacing e.g.

Works for most latest browsers in 2015. Simple solution. It doesn’t work for transparent, but unlike Thoronwen’s answer, I can’t get transparent to render with any size.

Noor Ali's user avatar

Simply put div inside the td and set the following styles of div :

Rafa Romero's user avatar

Nad's user avatar

Best way is to add <td> with a height attribute:

You can read more about colspan here.

In the following example, our table is green and our td with the height attribute is yellow:

Brhaka's user avatar

kiransr's user avatar

you can do something like on your table :

table selective: as it will select all tables, so if you want to select single table you can do likewise

For the above html you can do like this, note that for specific table if you want then you can use the below approach.

Sabaoon Bedar's user avatar

You can fill the <td/> elements with <div/> elements, and apply any margin to those divs that you like. For a visual space between the rows, you can use a repeating background image on the <tr/> element. (This was the solution I just used today, and it appears to work in both IE6 and FireFox 3, though I didn’t test it any further.)

Also, if you’re averse to modifying your server code to put <div/>s inside the <td/>s, you can use jQuery (or something similar) to dynamically wrap the <td/> contents in a <div/>, enabling you to apply the CSS as desired.

I realize this is an answer to an old thread and may not be the solution requested, but while all the suggested solutions did not do what I needed, this solution worked for me.

I had 2 table cells, one with background color, the other with a border color. The above solutions remove the border, so the cell on the right would appear to be floating in mid-air. The solution that did the trick was to replace the table , tr and td with divs and corresponding classes: table would be div , tr would be div and td would be div (change closing tags to divs as well obviously)

To get the solution for my problem the css is:

Hope this helps someone.

David Silva-Barrera's user avatar

The appearance of a row gap can be achieved by using a bottom border on the cells where there should be the next gap, i.e. border-bottom:solid white 5px;

Table with Row Gaps

Here is the code to create the screenshot:

Loathing's user avatar

Modern solution involving display:grid with grid-gap .

A modern solution to create a table would be using CSS grid or flexbox.

To add space between rows and columns, one can use grid-gap: [vertical] [horizontal] .

To prevent "too thick / double border" with zero grid-gap, one can add margin: -1px to the cell styling. Worth noticing: you will need this hack only if you have both borders and grid-gap of zero.

Space between columns is achieved in the same way. For example, 20px space between columns and 10px space between rows is done with this syntax: grid-gap: 10px 20px; .

Space inside rows / columns is achieved with paddings.

Tweakable demo

Below is an interactive demo, where you can tweak grid-gap, padding and turn on/off margin hack to see what changes.

Bonus: at the bottom you can find what code to insert for such behavior (regarding grid-gap, padding and margin hack)

nicael's user avatar

Here’s a simple and elegant solution, with a few caveats:

  • You can’t actually make the gaps transparent, you need to give them a specific color.
  • You can’t round the corners of the borders above & below the gaps
  • You need to know the padding and borders of your table cells

With that in mind, try this:

What you’re actually doing is sticking a rectangular ::before block into the top of all the cells in the row you want preceded by a gap. These blocks stick out of the cells a bit to overlap the existing borders, hiding them. These blocks are just a top and bottom border sandwiched together: The top border forms the gap, and the bottom border re-creates the appearance of the cells’ original top border.

Note that if you have a border around the table itself as well as the cells, you’ll need to further increase the horizontal -ve margin of of your ‘blocks’. So for a 4px table border, you’d instead use:

And if your table uses border-collapse:separate instead of border-collapse:collapse , then you’ll need to (a) use the full table border width:

. and also (b) replace the double-width of border that now needs to appear below the gap:

The technique is easily adapted to a .gapafter version, if you prefer, or to creating vertical (column) gaps instead of row gaps.

HTML таблицы — тег table

Таблица — один из основных инструментов для создания web-страниц.

Без использования CSS, только с помощью таблиц можно создавать страницы со сложным дизайном. Если вы прошли серию уроков Делаем сайт — первые шаги, то вы понимаете о чем речь.

Любая таблица представляет собой набор строк и столбцов, на пересечении которых находятся ячейки. Например:

Название таблицы

столбец 1 столбец 2 столбец 3
первый столбец первой строки второй столбец первой строки третий столбец первой строки
первый столбец второй строки второй столбец второй строки третий столбец второй строки
первый столбец третьей строки второй столбец третьей строки третий столбец третьей строки

Рассмотрим нашу таблицу с точки зрения HTML:

    сама таблица задается с помощью тегов <table></table>,

Создадим таблицу, где в качестве содержимого укажем пересечение номеров строк и столбцов:

Свойство border-spacing

Свойство border-spacing задает отступ между ячейками td или ячейками th HTML таблицы (и между границей ячейки и самой таблицы). Значением свойства служат любые единицы для размеров, кроме процентов.

Синтаксис

Значения

Значение Описание
одно значение Одно значения задает одинаковые отступы между ячейками по вертикали и по горизонтали.
два значения Первое значение задает отступ по горизонтали, а второе значение — отступ по вертикали.

Значение по умолчанию: 0 . Однако, каждый браузер имеет свое, ненулевое значение атрибута cellspacing , поэтому по умолчанию вы увидите отступы между ячейками.

Замечания

Применяйте свойство для таблиц, а не для ее ячеек (для ячеек не будет работать).

Аналогичного эффекта нельзя добиться с помощью margin , так как margin для ячеек таблицы не работает.

Если задано свойство border-collapse в значении collapse — border-spacing работать не будет.

Пример . Одно значение

Давайте сделаем отступы между ячейками (и между ячейкой и границей таблицы) в 10px :

Пример . Два значения

А теперь сделаем отступы в 10px по горизонтали и 30px по вертикали:

Пример . Зададим border-collapse: collapse

А вот теперь border-spacing работать не будет из-за свойства border-collapse в значении collapse :

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *