2016-03-15 61 views
0

,我不能拿出一個妥善的解決辦法奇特的要求:如何正確對齊表格單元格中的div而不包裝?

對於標有<div>表格單元格的內容,我怎麼能右對齊<div>同時防止整個小區從包裝?

這裏就是我有考慮:https://jsfiddle.net/c01y63k1/

table td:first-child { 
    white-space: nowrap; 
} 

table td:first-child > div { 
    margin-left: 1em; 
    display: inline-block; 
} 
<h2>This works:</h2> 
<table style="width: 200px"> 
    <tr> 
    <td> 
     Test test 
     <div> 
     float! 
     </div> 
    </td> 
    <td>Div with a lot of content</td> 
    </tr> 
</table> 

<h2>But...</h2> 
<p> 
Now my 'float!' is not right-aligned when there's extra space in the cell: 
</p> 

<table style="width: 500px"> 
    <tr> 
    <td> 
     Test test 
     <div> 
     float! 
     </div> 
    </td> 
    <td>Div with a lot of content</td> 
    </tr> 
</table> 

正如你所看到的,上面將工作當表格單元格的自動寬度將小於內容的展開寬度。但是,當表格單元格的寬度大於內容的寬度時,div將不會右對齊(因爲不是)。

div上應用float: right將以與上述情況相反的方式工作。看到這裏:https://jsfiddle.net/ycutor3t/

table td:first-child { 
    white-space: nowrap; 
} 

table td:first-child > div { 
    margin-left: 1em; 
    display: inline-block; 
    float: right 
} 
<h2>This does not work:</h2> 
<table style="width: 200px"> 
    <tr> 
    <td> 
     Test test 
     <div> 
     float! 
     </div> 
    </td> 
    <td>Div with a lot of content</td> 
    </tr> 
</table> 

<h2>But... this does!</h2> 
<p> 
Now my 'float!' is right-aligned when there's extra space in the cell: 
</p> 

<table style="width: 500px"> 
    <tr> 
    <td> 
     Test test 
     <div> 
     float! 
     </div> 
    </td> 
    <td>Div with a lot of content</td> 
    </tr> 
</table> 
+1

請添加[MCVE]你的問題。如果這些鏈接因任何原因停止工作,則問題變得不完整並且無法回答。 – ochi

+0

它不是浮動的,因爲你只是沒有浮動它,你只需在左邊添加一個邊距。無論如何,如果你不包裝「測試測試」文本,你想要什麼也許不起作用。 –

+0

我意識到這一點。我也有應用'float:right'的代碼。不幸的是,當單元格的寬度太小時它會被包裹起來。 –

回答

1

您可以使用Flexbox的

td:first-child { 
 
    display: flex; 
 
} 
 
td:first-child > div { 
 
    margin-left: auto; /* Push it to the right */ 
 
}
<table style="width: 500px"> 
 
    <tr> 
 
    <td> 
 
     Test test 
 
     <div>float!</div> 
 
    </td> 
 
    <td>Div with a lot of content</td> 
 
    </tr> 
 
</table>

+0

將表格單元格更改爲「display:flex」並不理想,但我想我可以將內容封裝在「div」中,並將樣式規則應用於此。 –

+0

@KevinLee是的,這有點奇怪。但它應該表現良好,將創建一個匿名錶格單元格,幷包裝'td' flex容器。 – Oriol