CSS ONLY:填充父</div>的<div>

时间:2014-03-19 00:57:32

标签: html css

enter image description here

我需要红色div来填充蓝色背景的父母。 http://jsfiddle.net/jiantongc/kyR8q/

.rowlevel2-deco上尝试了各种修复,但没有奏效: height:100%; box-sizing: border-box;等。

类似问题:Chrome doesn't honor row height if rowspan is present但没有实际工作解决方案。

4 个答案:

答案 0 :(得分:2)

.rowlevel2-deco{
    display: inline-block;
    padding: 0;
}

似乎工作。 http://jsfiddle.net/kyR8q/27/此外,要垂直居中,请使用:

.rowlevel2-deco:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

答案 1 :(得分:1)

您可以将height="1"添加到th

<th rowspan="2" class="rowlevel2" height="1">

比有一个小填充,通过添加padding:0;来删除它:

.rowlevel2 {
     background: blue; /* don't want to see blue */
     padding: 0;    
 } 

更新Chrome和FireFox

简短:明确指定从内容高度获取高度的所有父元素的高度,并且不要明确定义高度。

长:Thisthis让我觉得这是不可能的。但是this test适用于FF,而不适用于Chrome。此代码适用于:

* { padding:0; } /* All paddings be gone! This is not a padding problem */

table { height: 1px; } /* FF needs a height */

.foo {
    background: blue; /* Don't want to see blue */
    height: 100%; /* FF needs a height agian */
}

.bar {
    background: red;
    height:100%;
    width: 100px;
    display:inline-block; /* Chrome needs inline-block, FF doesn't care. */
}

.bar:before {
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
}

.ni {
    background: gray;
    width:120px;
    height:40px;
}

HTML:

<table>
    <thead>
        <tr>
            <th rowspan="2" class="foo">
                <div class="bar">Bar</div>
            </th>
            <th>
                <div class="ni">Knight 1</div>
            </th>
        </tr>
        <tr>
            <th>
                <div class="ni">Knight 2</div>
            </th>
        </tr>
    </thead>
</table>

http://jsfiddle.net/allcaps/V7jzL/2/

它也适用于your class names;)。

  

<percentage>指定百分比高度。百分比是   根据生成的框的高度计算   包含块。如果包含块的高度不是   明确指定(即,它取决于内容高度),以及这个   元素没有绝对定位,值计算为&#39; auto&#39;。

表格高度取决于内容高度== auto。因此,Mozilla希望在父元素上明确定义高度。 table { height: 1px; }.foo { height: 100%; } does that. 1px;`是一个小于任何普通表的值,内容高度无论如何都优先。将表推到合适的大小。

感谢@ {bjb568 display:inline-block; 感谢@KingKing .bar:before { content:''; ... }

答案 2 :(得分:0)

100%高度适用于绝对定位元素。所以CSS将是:

th.rowlevel2{
    background: blue; /* don't want to see blue */
    width: 100px;
    position: relative;
}

.rowlevel2-deco{
    background: red;
    height:100%;
    width: 100px;
    position: absolute;
    top: 0;
}

但在这种情况下,父必须定义宽度。

http://jsfiddle.net/aLQh7/1/

答案 3 :(得分:-1)

为什么不使用jQuery?

$(document).ready( function() {
    $('.rowlevel2-deco').
      css({
        'width': $('.rowlevel2').width(),
        'height': $('.rowlevel2').height()  
    });
});

垂直对齐红色div:

.rowlevel2-deco {
    background: red;
    display:table-cell;
    vertical-align: middle;
}

View it here