好像我在某处听到/读到 a 的<div>
内部<td>
是禁止的。并不是说它不起作用,只是它们的显示类型并不真正兼容。找不到任何证据来支持我的预感,所以我可能完全错了。
9 回答
使用div
instide atd
并不比使用表格进行布局的任何其他方式差。(有些人从不使用表格进行布局,而我恰好是其中之一。)
If you use a div
in a td
you will however get in a situation where it might be hard to predict how the elements will be sized. The default for a div is to determine its width from its parent, and the default for a table cell is to determine its size depending on the size of its content.
The rules for how a div
should be sized is well defined in the standards, but the rules for how a td
should be sized is not as well defined, so different browsers use slightly different algorithms.
在检查了XHTML DTD之后,我发现 <TD> 元素可以包含块元素,如标题、列表和 <DIV> 元素。因此,在 <TD> 元素内使用 <DIV> 元素不会违反 XHTML 标准。我很确定 HTML 的其他现代变体具有与 <TD> 元素等效的内容模型。
以下是相关的 DTD 规则:
<!ELEMENT td %Flow;>
<!-- %Flow; mixes block and inline and is used for list items etc. -->
<!ENTITY %Flow "(#PCDATA | %block; | form | %inline; | %misc;>
<!ENTITY %block "p | %heading; | div | %lists; | %blocktext; | fieldset | table">
表格单元可以合法地包含块级元素,因此它本质上不是错误的。当然,浏览器实现留下了一个推测性的理论立场。它可能会导致布局问题和错误。
虽然表格用于布局 - 有时仍然是 - 我想大多数浏览器都会正确呈现内容。甚至 IE。
If you want to use position: absolute; on the div with position: relative;
on the td you will run into issues. FF, safari, and chrome (mac, not PC though) will not position the div relative to the td (like you would expect) this is also true for divs with display: table-whatever;
so if you want to do that you need two divs, one for the container width: 100%;
height: 100%;
and no border so it fills the td without any visual impact. and then the absolute one.
other than that why not just split the cell?
I have faced the problem by placing a <div>
inside <td>
.
I was unable to identify the div using document.getElementById()
if i place that inside td. But outside, it was working fine.
As everyone mentioned, it might not be a good idea for layout purposes. I arrived to this question because I was wondering the same and I only wanted to know if it would be valid code.
Since it's valid, you can use it for other purposes. For example, what I'm going to use it for is to put some fancy "CSSed" divs inside table rows and then use a quick jQuery function to allow the user to sort the information by price, name, etc. This way, the only layout table will give me is the "vertical order", but I'll control width, height, background, etc of the divs by CSS.
Two ways of dealing with it
- put
div
insidetbody
tag - put
div
insidetr
tag
Both approaches are valid, if you see feference: https://stackoverflow.com/a/23440419/2305243
它破坏了语义,仅此而已。它工作得很好,但是如果你“破坏语义”,可能会有屏幕阅读器或其他东西不会喜欢处理你的 HTML。