Html 使 <div> 的背景颜色填充封闭的 <td>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8344850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:46:06  来源:igfitidea点击:

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

htmlcsshtml-tablealignment

提问by RichieHindle

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

我有一个 HTML 表格,其单元格包含divs display:inline-block,包含不同大小的文本。

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 doesfill the cell, but it doesn't for the smaller fonts:

我需要文本在基线上对齐,我需要divs的背景颜色来填充单元格的高度。对于最大的字体,背景颜色填充单元格,但对于较小的字体则不会:

How it looks in Firefox

它在 Firefox 中的外观

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

这可能吗?明显的解决方案div { height:100% }似乎被不同的字体大小所破坏。

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.

它也在 jsfiddle here 上

回答by ptriek

Not perfect, but the closest I could get:

不完美,但我能得到的最接近:

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

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

回答by AlienWebguy

Quick and dirty fix:

快速和肮脏的修复:

CSS

CSS

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

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

演示:http: //jsfiddle.net/2YbBg/

回答by JercSi

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

我读过一次,td没有报告它的高度。所以任何height: 100%orheight:auto等等都不起作用。

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

所以我的解决方案在这里:http: //jsfiddle.net/UGTYP/

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

它使用javascript将“粉红色”文本的高度更改为“黄色”div的高度。