2013-07-12 88 views
13

下面是一个例子:填充顶部与父宽度相关的百分比如何?

http://jsfiddle.net/QZAd8/1/

通知如何将所有的红色的div是相同height和具有padding-top:100%;,但它们甲& B具有不同的填充大小...和它看来,宽度的父项更改此值(请注意,C会更改父项的height,但不会更改填充)。

为什么这种填充与宽度有关?

编辑:由于历史原因,在案件的jsfiddle消失了,我在我的例子中使用的代码如下......

.outer { 
 
    background-color: green; 
 
    height: 300px; 
 
    width: 70px; 
 
    float: left; 
 
    margin-right: 10px; 
 
} 
 

 
.middle { 
 
    background-color: red; 
 
    height: 100px; 
 
    width: 50px; 
 
    padding-top: 100%; 
 
} 
 

 
.inner { 
 
    background-color: blue; 
 
    height: 3px; 
 
    width: 100%; 
 
}
<div class='outer'> 
 
    <div class='middle'> 
 
    A 
 
    <div class='inner'> 
 
    </div> 
 
    </div> 
 
</div> 
 

 
<div class='outer' style='width:100px'> 
 
    <div class='middle'> 
 
    B 
 
    <div class='inner'> 
 
    </div> 
 
    </div> 
 
</div> 
 

 
<div class='outer' style='height:400px'> 
 
    <div class='middle'> 
 
    C 
 
    <div class='inner'> 
 
    </div> 
 
    </div> 
 
</div>

回答

21

CSS fluid layout: margin-top based on percentage grows when container width increases

在CSS中,所有四个margin:和padding:百分比都是相对于宽度的......尽管这可能看起来毫无意义。这只是CSS规范的方式,对此你无能为力。

Straight from the horse's mouth

'padding-top', 'padding-right', 'padding-bottom', 'padding-left' 
Value:  <padding-width> | inherit 
Initial: 0 
Applies to:  all elements except table-row-group, table-header-group, table-footer-group, table-row, table-column-group and table-column 
Inherited:  no 
Percentages: refer to width of containing block 
Media:  visual 
Computed value:  the percentage as specified or the absolute length 

率:是指包含块

+1

不错。多么意外......感谢您的发现! –

1

的方式与宽度确实是填充p百分比是相对于宽度的,但具体而言,padding: 100%也可以被读为padding: *width-of-container*px

Ç块具有70px的宽度。应用padding: 100%padding: 70px相同