- Method 1
- Method 2
- Set Cellpadding
- Set Cellspacing
- Setting Cellspacing and Cellspacing both
- Summary
- Top comments (0)
- Read next
- GPT Web App Generator — Let AI create a full-stack React & Node.js codebase based on your description 🤖🤯
- Common design patterns at Stripe
- How to Build a Fancy Testimonial Slider with Tailwind CSS and Vue
- How to Build a Fancy Testimonial Slider with Tailwind CSS and Alpine.js
- More from RajeshKumarYadav.com
- Учимся применять cellpadding и cellspacing в CSS
- Основы
- Проблемы с IE ниже 7 версии
- Установки по умолчанию
- Cellpadding
- Cellspacing
- Комбинация свойств
- Комбинация свойств (дополнительно)
- How to Set Cellpadding and Cellspacing in CSS
- How to adjust spacing separately for the top, right, left, and bottom of each cell?
- Table Cellpadding and Cellspacing with CSS
Method 1
This property will even allow separate horizontal and vertical spacing, something you couldn’t do with old-school «cellspacing».
Method 2
table border-collapse: collapse;> td padding: 0px;>
Set Cellpadding
table border-collapse: collapse;> td padding: 6px;>
So that it will look like as —
Set Cellspacing
table border-spacing: 2px;> td padding: 0px;>
So that it will look like as —
Setting Cellspacing and Cellspacing both
table border-spacing: 8px 2px;> td padding: 6px;>
So that it will look like as —
table border-spacing: 2px;> td padding: 6px;>
So that it will look like as —
Summary
table border-collapse: collapse; /* 'cellspacing' equivalent */ > table td, table th padding: 0; /* 'cellpadding' equivalent */ >
With all that being said, I highly recommend you keep learning! Thank you for reading this article. Please feel free to connect with me on LinkedIn and Twitter.
Top comments (0)
Read next
GPT Web App Generator — Let AI create a full-stack React & Node.js codebase based on your description 🤖🤯
Common design patterns at Stripe
How to Build a Fancy Testimonial Slider with Tailwind CSS and Vue
How to Build a Fancy Testimonial Slider with Tailwind CSS and Alpine.js
I am Rajesh, a Software Engineer by profession and a Technical Blogger by passion. I am passionate about knowledge sharing, open-source contributions, connecting to people, and mentoring.
More from RajeshKumarYadav.com
Once suspended, rajeshkumaryadavdotcom will not be able to comment or publish posts until their suspension is removed.
Once unsuspended, rajeshkumaryadavdotcom will be able to comment and publish posts again.
Once unpublished, all posts by rajeshkumaryadavdotcom will become hidden and only accessible to themselves.
If rajeshkumaryadavdotcom is not suspended, they can still re-publish their posts from their dashboard.
Once unpublished, this post will become invisible to the public and only accessible to RajeshKumarYadav.com.
They can still re-publish the post if they are not suspended.
Thanks for keeping DEV Community safe. Here is what you can do to flag rajeshkumaryadavdotcom:
rajeshkumaryadavdotcom consistently posts content that violates DEV Community’s code of conduct because it is harassing, offensive or spammy.
Unflagging rajeshkumaryadavdotcom will restore default visibility to their posts.
DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey.
Built on Forem — the open source software that powers DEV and other inclusive communities.
Made with love and Ruby on Rails. DEV Community © 2016 — 2023.
We’re a place where coders share, stay up-to-date and grow their careers.
Учимся применять 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
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.
Table Cellpadding and Cellspacing with CSS
- by Louis Lazaris
- September 24, 2022
In the past, when doing table-based layouts, or when creating data tables in HTML, it was common to remove unnecessary padding and spacing that’s included in tables by the browser as a default.
This would be done as follows:
table cellpadding="0" cellspacing="0">Code language: HTML, XML (xml)
While these features still work for backwards-compatibility reasons, and are often used in HTML email, the cellpadding and cellspacing attributes are now obsolete.
To correctly do cellpadding and cellspacing with CSS, you can do the following:
Code language: CSS (css)table < border-collapse: collapse; border-spacing: 0; > td < padding: 0; >
You can see this in use in the following interactive CodePen:
If you want to include some cellspacing, then you would set border-collapse to its default value and add a non-zero value to border-spacing .
Code language: CSS (css)table < border-collapse: separate; /* You can exclude this line, this is the default */ border-spacing: 14px; > td < padding: 20px; >
This would be useful if you want “margins” on table cells, since the margin property doesn’t work on table cells. The demo below demonstrates:
Note: To the best of our knowledge, the information above and the snippet are accurate and up to date. However, in case you notice something wrong, please report snippet or leave a comment below.
Louis Lazaris is a writer, speaker, author, and front-end web developer who’s been involved in the web development industry in various forms since 2000. He blogs about code on his primary website and curates a series of newsletters for tech professionals and software developers.
Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!
- 50+ Best Free WordPress Themes
- How to Make a WordPress Website: Ultimate Guide
- Best WordPress Hosting
- Best Cheap WordPress Hosting
- Managed WordPress Hosting Guide
- Top 5 eCommerce Hosting Solutions
- Best Web Hosting for Small Business
- Best eCommerce Platforms
- Best Email Marketing Tools
- Best SMTP Providers Compared
- Best Live Chat Software Solutions
- How to Build Your Own Website