Make the background-color of a <div> fill the enclosing <td>

末鹿安然 提交于 2020-01-14 07:24:33

问题


I have an HTML table whose cells contain divs with display:inline-block, containing text of varying sizes.

I need the text to align on the baseline, and I need the background colors of the divs to fill the height of the cells. For the largest font, the background color does fill the cell, but it doesn't for the smaller fonts:

Is this possible? Obvious solutions like div { height:100% } seem to be scuppered by the varying font sizes.

Here's the code so far:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <style type="text/css">
    table td {
        vertical-align: baseline;
        padding: 0;
    }

    td div {
        display: inline-block;
    }
  </style>
</head>
<body>
    <table>
        <tr>
            <td style="background-color:cyan">
                <div style="background-color:pink;">Pink</div>
                <div style="background-color:green;">Green</div>
            </td>
            <td style="background-color:cyan">
                <div style='font-size: 40pt; background-color:yellow;'>
                    Big yellow text
                </div>
            </td>
            </tr>
  </table>
</body>
</html>

It's also on jsfiddle here.


回答1:


Not perfect, but the closest I could get:

http://jsfiddle.net/gfPkV/14/




回答2:


Quick and dirty fix:

CSS

div {
    line-height:60px;
    height:60px;
    vertical-align:middle;
}

Demo: http://jsfiddle.net/2YbBg/




回答3:


I read once, that td does not report it's height. So any height: 100% or height:auto, etc.. won't work.

So my solution is here: http://jsfiddle.net/UGTYP/

It changes height of "pink" text to the height of "yellow" div with javascript.



来源:https://stackoverflow.com/questions/8344850/make-the-background-color-of-a-div-fill-the-enclosing-td

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!