Css border radius with border collapse

Свойство CSS3 border-radius и border-collapse: collapse не смешиваются. Как я могу использовать border-radius для создания свернутой таблицы с закругленными углами?

Изменить — Исходное название: Есть ли альтернативный способ достижения border-collapse:collapse в CSS (для того, чтобы иметь свернутую округленную таблицу углов)? Так как оказывается, что простое ограничение границ таблицы не решает проблему с корнем, я обновил заголовок, чтобы лучше отразить обсуждение. Я пытаюсь создать таблицу с закругленными углами, используя свойство CSS3 border-radius . Стили таблицы, которые я использую, выглядят примерно так:

  • Это очень легкий сайт, и я бы хотел, чтобы JavaScript был максимально минимальным
  • часть обращения, использующего радиус границы, для меня — грациозная деградация и прогрессивное совершенствование. Используя граничный радиус для всех закругленных углов, я надеюсь иметь последовательно округленный сайт в браузерах с поддержкой CSS3 и последовательно квадратный сайт в других (я смотрю на вас, IE).
Читайте также:  Threading python run function

Я знаю, что попытка сделать это с помощью CSS3 сегодня может показаться ненужной, но у меня есть причины. Я также хотел бы отметить, что эта проблема является результатом спецификации w3c, а не плохой поддержки CSS3, поэтому любое решение будет по-прежнему актуальным и полезным, когда CSS3 будет иметь более широкую поддержку.

Плагин jquery.corner предоставляет хорошую альтернативу: http://www.malsup.com/jquery/corner/ имеет хорошую демонстрацию своих возможностей. Вы можете указать, какие углы изменить и какой стиль изменения вы хотите выполнить, определив радиус и т. Д.

Не могли бы вы обернуть таблицу в div, установить border-radius и «overflow: hidden» в div? Я только что проверил, и это прекрасно работает, если вам не нужно прокручивать / расширять в div, который имеет фиксированную ширину / высоту или его родителей, которые делают.

Этот вопрос был задан в 2009 году. Я немного удивлен, что в 2015 году нет лучших решений, чем перечисленные ниже. W3C должен был это исправить несколько лет назад.

Источник

CSS3�s border-radius property and border-collapse:collapse don�t mix

Let’s explore an alternative way to achieve border-collapse:collapse with border-radius in CSS to have a collapsed, rounded corner table.

How can I use border-radius to create a collapsed table with rounded corners?

Making rounded corners can be accomplished using border-radius:10px . Some example CSS:

To reduce the CSS and require targeting a combination of table, th, and td tags it can be handy to apply border-collapse:collapse so the browser draws a single border and not one for each the table, tr, and td tags.

Solution to a collapsed rounded corner table

When applying the combination of collapse with the border radius, some td elements were not being rounded. The solution is to target the specific ones, in this case the first and last td elements:

 table tr:last-child td:first-child < border-bottom-left-radius: 10px; >table tr:last-child td:last-child

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Jamie Munro

Jamie began his writing career in 2009. As the success of Jamie’s blog grew, he turned his writing passion to books about web development in hopes that his many years of experience could be passed on to his readers.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you’re looking to learn, I’ve hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can’t wait for you to dig in and improve your skillset with any of the tutorials below.

Front-End

Server-Side

Database

© 2009 — 2023 EndYourIf.com — If you wish to share the content, please include a link back! Privacy Policy

Источник

CSS Rounded Table Corners

Let’s assume you have a website theme that requires having rounded corners for elements including tables. Let’s see how we can achieve them and what are the challenges in achieving so.

Let’s create a simple table.

 
Name Department Office
John Admin North
Smith Logistics South
David Transport East

Let’s add some basic styling to it using background-color , color , and padding properties. We also remove the spacing between the internal borders using border-spacing: 0 (not by using border-collapse — this is important for out rounded corners).

Name Department Office
John Admin North
Smith Logistics South
David Transport East

Rounding The Outer Corners

Let’s next add a border-radius to get our rounded corners.

table.rounded-corners < border-spacing: 0; border-collapse: separate; border-radius: 10px; >table.rounded-corners th, table.rounded-corners td

Whoa, the corners didn’t get rounded! Well, the corners of the background got rounded, but not the border. This is because the borders of the table cells didn’t get rounded — they stayed square. Lets take a look if we applied the border to the outside of the table, and removed it from the individual cells:

Now all we need to do is add back the internal borders, but not round the outside edges of the cells. If you take another look at the previous tables, you will also see that the interal borders are 2px wide. This is because we are using border-collapse: separate which means each cell has its own 1px border, which touches the 1px border from the next cell. Unfortunately we can’t just set the border width to 0.5px. However, we can rely on the content model of the table to help us construct some funky selectors that will work for all tables. The following snippet will work for any well-structured table, including tables with captions, colgroups, tbody, no tbody etc.

 table.rounded-corners < border-spacing: 0; border-collapse: separate; border-radius: 10px; border: 1px solid black; >/* Apply a border to the right of all but the last column */ table.rounded-corners th:not(:last-child), table.rounded-corners td:not(:last-child) < border-right: 1px solid black; >/* Apply a border to the bottom of all but the last row */ table.rounded-corners>thead>tr:not(:last-child)>th, table.rounded-corners>thead>tr:not(:last-child)>td, table.rounded-corners>tbody>tr:not(:last-child)>th, table.rounded-corners>tbody>tr:not(:last-child)>td, table.rounded-corners>tfoot>tr:not(:last-child)>th, table.rounded-corners>tfoot>tr:not(:last-child)>td, table.rounded-corners>tr:not(:last-child)>td, table.rounded-corners>tr:not(:last-child)>th, table.rounded-corners>thead:not(:last-child), table.rounded-corners>tbody:not(:last-child), table.rounded-corners>tfoot:not(:last-child)

This is starting to look good now. You could probably stop there if that’s all you need. If you want to style the backgrounds of individual cells or rows (e.g. alternating colors or highlighting rows on hover) then we’ll sort that out first. Lets just change the background color of our header row to something really nice to make it stand out:

And we just broke our nice rounded corners again. Remember we didn’t round the corners of the individual cells, just the table itself. Thankfully, although the fix was a little bit tricky for the borders, it’s much easier for the background. We can just set the overflow on the whole table to hidden to hide the bit that sticks out over the rounded corners. We’ve used a CSS variable here just to remove the duplication on the border style.

 table.rounded-corners < /* Change these properties */ --border: 1px solid black; border-radius: 10px; /* Don't change these properties */ border-spacing: 0; border-collapse: separate; border: var(--border); overflow: hidden; >/* Apply a border to the right of all but the last column */ table.rounded-corners th:not(:last-child), table.rounded-corners td:not(:last-child) < border-right: var(--border); >/* Apply a border to the bottom of all but the last row */ table.rounded-corners>thead>tr:not(:last-child)>th, table.rounded-corners>thead>tr:not(:last-child)>td, table.rounded-corners>tbody>tr:not(:last-child)>th, table.rounded-corners>tbody>tr:not(:last-child)>td, table.rounded-corners>tfoot>tr:not(:last-child)>th, table.rounded-corners>tfoot>tr:not(:last-child)>td, table.rounded-corners>tr:not(:last-child)>td, table.rounded-corners>tr:not(:last-child)>th, table.rounded-corners>thead:not(:last-child), table.rounded-corners>tbody:not(:last-child), table.rounded-corners>tfoot:not(:last-child)

And there we have it. We now have our rounded table corners with an easy copy/paste snippet

Rounding Internal Corners

While the above works great if all you want to do is round the outer 4 corners of the table, it doesn’t work so well if you want to round any of the other corners. Lets say, for example, you wanted to round the corners of the table headings so it looks separate from the body. If we use the previous trick using overflow: hidden , then the background will show outside the rounded corners between the heading and the body. We can easily fix this by applying the background to the individual cells, but we now have the problem of actually creating the border around these rounded corners. We can apply the border to the individual cells, but then we get the minimum 2px internal borders. If we just apply the border to one side of each cell boundary, then we lose part of the border on the internal rounded corners:

Name Department Office
John Admin North
Smith Logistics South
David Transport East

It almost works perfectly, apart from these bits here:

Broken Rounded Corners

Box Shadow To The Rescue

Instead of using borders, we can use a little trick involving a box-shadow on every cell to create the effect that we’re after. It actually makes our border code surprisingly simple:

table.rounded-corners < /* We need this to be able to use border-radius. */ border-collapse: separate; /* Add a 1px border spacing for out box-shadow to fit into. Increase this if you want to increase the border width. */ border-spacing: 1px; >table.rounded-corners th, table.rounded-corners td < /* Remove any borders from our stylesheet. */ border: 0; /* Use the spread value on the box-shadow to set the border width. */ box-shadow: 0 0 0 1px black; > 

Now we can style the rest of the cells and round their corners as much as we want:

 table.rounded-corners thead tr:first-child th:first-child < border-top-left-radius: 10px; >table.rounded-corners thead tr:last-child th:first-child < border-bottom-left-radius: 10px; >table.rounded-corners thead tr:first-child th:last-child < border-top-right-radius: 10px; >table.rounded-corners thead tr:last-child th:last-child < border-bottom-right-radius: 10px; >table.rounded-corners tbody tr:first-child td:first-child < border-top-left-radius: 10px; >table.rounded-corners tbody tr:last-child td:first-child < border-bottom-left-radius: 10px; >table.rounded-corners tbody tr:first-child td:last-child < border-top-right-radius: 10px; >table.rounded-corners tbody tr:last-child td:last-child

And the results are just right

Name Department Office
John Admin North
Smith Logistics South
David Transport East

Conclusion

Rounding the corners of a table appears to be a simple task but it can easily get tricky based on your requirements. If you are only rounding the corners of the whole table, a border-radius will get the job done. But if you need to round the header and body separately, or even round the individual table rows in the body, then you can get the job done with a box-shadow .

UnusedCSS helps website owners remove their unused CSS every day. See how much you could save on your website:

You Might Also Be Interested In

Источник

HTML Table Borders

HTML tables can have borders of different styles and shapes.

How To Add a Border

To add a border, use the CSS border property on table , th , and td elements:

Example

Collapsed Table Borders

To avoid having double borders like in the example above, set the CSS border-collapse property to collapse .

This will make the borders collapse into a single border:

Example

Style Table Borders

If you set a background color of each cell, and give the border a white color (the same as the document background), you get the impression of an invisible border:

Example

table, th, td <
border: 1px solid white;
border-collapse: collapse;
>
th, td <
background-color: #96D4D4;
>

Round Table Borders

With the border-radius property, the borders get rounded corners:

Example

Skip the border around the table by leaving out table from the css selector:

Example

Dotted Table Borders

With the border-style property, you can set the appearance of the border.

The following values are allowed:

Example

Border Color

With the border-color property, you can set the color of the border.

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.

Источник

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