- Что является аналогом colspan при использовании display: table; в CSS?
- 6 ответов
- Rowspans & Colspans in CSS Tables
- Nothing Up My Sleeve…
- Sleight of Hand and Absolute Positioning
- Share This Article
- CSS Colspan/Rowspan for elements whose display is set to table-cell
- CSS Style
- HTML Body
- Related
- Merge HTML Table Cells Vertically with Rowspan
- Syntax
- Rowspan Examples
- Adding Rowspan To An Existing Table
- Which cell has to be removed exactly?
- Rowspan in the last row of the table
- Colspan and Rowspan For Table Cells
- Colspan For Div Tables
- HTML Table Colspan & Rowspan
- HTML Table — Colspan
- Example
- HTML Table — Rowspan
- Example
- HTML Exercises
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Что является аналогом colspan при использовании display: table; в CSS?
но, как я уже сказал, мне не разрешено использовать традиционные теги таблицы ( table , tr , td , th ). Здесь JSFIddle того, что у меня есть на данный момент. Как я могу получить тот же результат, что и с , но, используя только divs и CSS. редактирует:
* Ширина ячейки таблицы в одной строке не должна быть фиксированной, она должна быть динамической, и должно быть возможно сделать их (ячейки) разной шириной (в одной строке).
* Ширина ячейки таблицы в разных строках того же столбца должна быть равна. Как в традиционной таблице. Только ширина ячейки «colspanned» должна быть разной.
6 ответов
Как указано в спецификации CSS 2.1 в части «17.5 Визуальный макет содержимого таблицы»
Ячейки могут занимать несколько строк или столбцов. (Хотя CSS 2.1 не определяет, как определяется количество строк или столбцов.
Поэтому он отвечает легко! Не думайте о таблицах css точно так же, как html-таблицы. Поскольку есть некоторые отличия, как то, что упоминалось в «17.2.1 Анонимные табличные объекты» :
. для того, чтобы модель таблицы работала, необходимо принять «недостающие» элементы. Любой элемент таблицы автоматически генерирует необходимые анонимные объекты таблицы вокруг себя, состоящие из по меньшей мере трех вложенных объектов, соответствующих элементу ‘table’/’inline-table’, элементу ‘table-row’ и элементу ‘table-cell’.
Итак, вы можете сделать это таким образом (каждая строка как таблица и сброшенная таблица-строка для исключения ненужного блока div), пока не укажу способ определения количества строк или столбцов:
One Two Three Four Five Six One Two Three Four Five Six One Two Three Four Five Six
Rowspans & Colspans in CSS Tables
If you were to guess who recently made that statement you’d be forgiven for thinking it came from the Opera, Safari, or Firefox team; they have always seemed to be the most standards-conscious browser vendors. In fact, this quote comes from Doug Stamper of Microsoft, regarding Internet Explorer 8.
It seems the very thing web designers have been asking for—mature support for CSS2.1 across all major browsers—is actually about to happen. Back in Tech Times #185, I wrote about what this would mean to web designers in Table-Based Layout Is The Next Big Thing . In short, I said that CSS tables would become the best tool for CSS page layout.
There were mixed reactions to that article, particularly on the point of row and column spans. HTML tables let you create cells that span multiple rows or columns, but CSS tables don’t provide that same freedom.
Well, in my research for an as yet unannounced, potentially controversial book on CSS, I’ve figured out how to simulate row and column spans in CSS tables. Rather than make you wait for the book, I thought I’d show you this useful technique right away!
Nothing Up My Sleeve…
If you’ve had experience building layouts using HTML tables, you’ll be familiar with the use of the colspan and rowspan attributes of the td element. These attributes offer complex possibilities to a simple table, enabling cells to span columns and rows.
CSS tables lack any concept of row or column spanning, making it trickier to use one single layout structure than what might have been possible when using tables. However, similar layouts can be achieved by using nested CSS tables.
Of course, nested tables are not a perfect solution. When you want to match the dimensions of cells across nested tables, for example, things can get messy in a hurry, and the extra tags really start to add up.
As it turns out, it’s also possible to simulate row and column spanning using absolute positioning of table cells, in many cases. In this example, we’ll make the second cell of the first row of a table span both rows of the table (as if it had a rowspan of 2 ). First, let’s take a look at the HTML code:
Top left Center Top right Bottom left Bottom right
You’ll notice that we’ve wrapped our table div in an extra div with a class of «tablewrapper» . This extra div is needed to provide a CSS positioning context—which we create by giving it relative positioning:
According to the CSS spec, we should be able to simply apply relative positioning to the table div , but current browsers don’t seem to support this.
Sleight of Hand and Absolute Positioning
Now, we can use absolute positioning to control the size and position of the div with class «rowspanned cell» :
With the top and bottom properties both set to zero, the cell will stretch to fill the full height of the table, simulating a row span. Depending on the needs of your layout, you could use different values for top and bottom , or even set the cell’s height directly to achieve other row-spanning layouts.
You also need to specify the width of the cell. Usually, the easiest way to do this is just to set its width property, but depending what you know of the dimensions of surrounding table cells, you could also do this by setting left and right .
Since the positioned cell doesn’t actually span multiple rows of the table, the table must still contain a corresponding cell in each of the other rows. These cells are simply empty placeholders, though; note the div with class «empty cell» in the HTML code above. The function of this cell is to hold open the space that will be occupied by the “spanned” cell, so we must ensure its width matches the width we specified for the «rowspanned cell» :
And that’s all there is to it! To complete the style sheet for this example, we need only set the appropriate display property values, and add some borders so we can see what’s going on:
.tablewrapper < position: relative; >.table < display: table; >.row < display: table-row; >.cell < border: 1px solid red; display: table-cell; >.cell.empty < border: none; width: 100px; >.cell.rowspanned
In essence, by using absolute positioning we are telling the browser, “Let me handle the layout of this table cell—you take care of the rest.” Here’s what the results look like:
Try it for yourself. This example works in all major browsers except for Internet Explorer 7, and also works in the current IE8 Beta 2 release.
What do you think? Can you see yourself switching to CSS tables for layout as your Internet Explorer users make the move to IE8?
Share This Article
Kevin Yank is an accomplished web developer, speaker, trainer and author of Build Your Own Database Driven Website Using PHP & MySQL and Co-Author of Simply JavaScript and Everything You Know About CSS is Wrong! Kevin loves to share his wealth of knowledge and it didn’t stop at books, he’s also the course instructor to 3 online courses in web development. Currently Kevin is the Director of Front End Engineering at Culture Amp.
CSS Colspan/Rowspan for elements whose display is set to table-cell
The following tutorial shows you how to use CSS to do «CSS Colspan/Rowspan for elements whose display is set to table-cell».
CSS Style
The CSS style to do «CSS Colspan/Rowspan for elements whose display is set to table-cell» is
.table < display:table; > .row < display:table-row; > .cell < display:table-cell; > .colspan < max-width:1px; overflow:visible; >
HTML Body
body> div >"table"> div >"row"> div >"cell colspan"> spanning !-- w w w . d e m o 2 s. c o m --> div >"cell"> div >"cell"> div >"row"> div >"cell"> 1 div >"cell"> 2 div >"cell"> 3
The following iframe shows the result. You can view the full source code and open it in another tab.
html> head> title>css column spanning meta name="viewport" content="width=device-width, initial-scale=1"> style id="compiled-css" type="text/css"> .table !-- w w w . d em o 2 s . c om --> display: table; > .row < display: table-row; > .cell < display: table-cell; > .colspan < max-width: 1px; overflow: visible; > body> div >'table'> div >'row'> div >'cell colspan'> spanning div >'cell'> div >'cell'> div >'row'> div >'cell'>1 div >'cell'>2 div >'cell'>3
Related
- CSS use display: table-cell and have a fixed width/height
- CSS Cannot define the height or width of a DIv set to display:table-cell
- CSS Child div display table-cell fixed width
- CSS Colspan/Rowspan for elements whose display is set to table-cell
- CSS Colspan/Rowspan for elements whose display is set to table-cell (Demo 2)
- CSS Colspan/Rowspan for elements whose display is set to table-cell (Demo 3)
- CSS Cross browser full height element within display:table-cell
demo2s.com | Email: | Demo Source and Support. All rights reserved.
Merge HTML Table Cells Vertically with Rowspan
Define high table cells that span two or more rows using the colspan attribute. Similarly to the colspan attribute, we can assign this HTML tag attribute to th header and td cell tags in the body and footer.
Syntax
Rowspan has to be a number, greater than the default 1, that shows how many rows spans the cell towards the bottom.
Rowspan Examples
A head rowspan="2">B head C head rowspan="2">X Y Z
⏰ Jeff Elon Bill Warren 1 rowspan="5">1-5 rowspan="3">1-3 1 1 2 rowspan="3">2-4 2 3 rowspan="3">3-5 4 4 5 5 5
Adding Rowspan To An Existing Table
Most visual HTML table generators don’t support setting the rowspan easily. Usually you need to create the code for a plain X×Y table, then using some WYSIWYG HTML editor, you have to manually add the rowspan attribute, and remove the unwanted cells that are pushed out by the enlarged cell.
Warning thrown by W3 HTML Validator for incorrect rowspan declaration.
Dealing with rowspans is a little harder than adding colspans because increasing a colspan you just have to delete the next cell(s) in the same row. Adding rowspan however you need to calculate exactly which cell has to be removed in the next row.
Adding rowspan=»2″ to the E cell pushes out the I cell which has to be removed.
A B C D rowspan="2">E F G H class="brick">I J K L
Which cell has to be removed exactly?
When we set the rowspan of a cell to 2, we have to delete a cell in the next row (demonstrated above)
When we set the rowspan of a cell to 3, we have to delete a cell in 2 rows below.
A B C D rowspan="3">E F G H class="brick">I J K class="brick">L
Rowspan in the last row of the table
Increasing the rowspan of a table cell in the last row would push the bottom of the table down, making the cell to stick out. Doing this is incorrect and the W3 Validator throws the following error.
Colspan and Rowspan For Table Cells
Rowspan is used to extend a cell to the bottom. We can also use the colspan attribute to spread out to the right. You can combine the rowspan and colspan to create complex tables. Learn more about colspan on its dedicated page.
A B C D E F colspan="3" class="brick">Colspan=3 G G rowspan="3" class="brick">Row span =3 H I J K L M N O P Q R S T U W
Assigning both rowspan and colspan to the same cell will extend it both vertically and horizontally. The exemple below will create a 2×2 cell.
A B C D E colspan="2" rowspan="2" class="brick"> 2x2 F G H I J K L
Colspan For Div Tables
HTML tables can be replaced by structured tags. Unfortunately we can’t just simply add rowspan=»x» to a Div table cell. Rowspan and colspan attributes can be added to td and th cells only.
The best way to extend table cells in a div table is to use nested tables, but each case might be different. We are going to present an increased colspan in a div table through an example.
Let’s say we have a 3×3 div table, where we need to push the highlighted E cell to the bottom to annex it to the H cell.
class="divTable"> class="divTableBody"> class="divTableRow"> class="divTableCell">A class="divTableCell">B class="divTableCell">C class="divTableRow"> class="divTableCell">D class="divTableCell brick">E class="divTableCell">F class="divTableRow"> class="divTableCell">G class="divTableCell">H class="divTableCell">I
HTML Table Colspan & Rowspan
HTML tables can have cells that span over multiple rows and/or columns.
HTML Table — Colspan
To make a cell span over multiple columns, use the colspan attribute:
Example
Note: The value of the colspan attribute represents the number of columns to span.
HTML Table — Rowspan
To make a cell span over multiple rows, use the rowspan attribute:
Example
Note: The value of the rowspan attribute represents the number of rows to span.
HTML Exercises
COLOR PICKER
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.