问题
Following is my table structure:
<table border="1">
<tbody>
<tr>
<td class="new_doc" colspan="7">
Add a New Document
</td>
</tr>
<tr>
<th>Sl</th>
<th>Name</th>
<th>Path</th>
<th>Date</th>
<th>Status</th>
<th>User</th>
<th>Share</th>
</tr>
</tbody>
</table>
I want the content of the td with class new_doc to be right aligned.
Initially I tried with float:right;
which gave me an unexpected result. But when I tried with text-align: right;
it gave me the desired output.
Why they are behaving entirely different for a td ?
Following are the fiddle:
float: right
text-align: right
回答1:
Tables and table cells have a unique formatting structure which, in CSS, is described in an entire section of its own.
Attempting to float a table cell will interfere with this structure, as it quite literally causes it to no longer be a table cell — it turns it into a block box instead, causing HTML attributes such as colspan
as in your markup to no longer apply:
Note. Positioning and floating of table cells can cause them not to be table cells anymore, according to the rules in section 9.7. When floating is used, the rules on anonymous table objects may cause an anonymous cell object to be created as well.
Browsers following the CSS spec on formatting tables have to follow specific rules on how to handle such cases in order to preserve a relatively sane table structure according to the CSS table formatting model. Specifically, what you see when using float
is that the first td
, which is now a (floating) block box, is automatically contained in an anonymous table cell within the first tr
. Note that this anonymous cell does not inherit the colspan
attribute from your markup; the attribute simply stops applying altogether. Since there are no other cells in the first tr
, the rest of it is left blank. Once the first tr
has been formatted, the second tr
is then constructed as normal.
Of course, since you're looking to align the text content of your table cell, it only makes sense to use the text-align
property to do so.
来源:https://stackoverflow.com/questions/23333176/why-float-and-text-align-behave-different-in-a-td