2017-02-04 130 views
1

我根据另一个高度匹配一个div的高度。第一个div有纵横比,因此只能从填充底部获得高度。我匹配第二个使用相同的CSS,但注意到滚动条滚动内容或不需要时出现。滚动条滚动过去内容(没有指定高度,只填充底部)

CSS:

.one { 
    display: inline-block; 
    height: 0px; 
    width: 200px; 
    padding-bottom: calc(.5625 * 200px); /* aspect ratio 56.25% of width */ 
    background-color: white; 
} 

.two { 
    margin-left: 15px; 
    display: inline-block; 
    height: 0px; 
    width: 200px; 
    padding-bottom: calc(.5625 * 200px); /* aspect ratio 56.25% of width */ 
    background-color: white; 
    overflow-y: auto; /* scroll on overflow if needed */ 
} 

这里是一个小提琴:

https://jsfiddle.net/m88stpf4/3/

+0

额外的空间是填充-bottom ... – sol

回答

1

垂直滚动条出现的原因是子元素的高度添加到父元素的计算填充中。

最简单的解决办法是子元素的高度设置为inherit,这样它会继承0父元素的高度:

Updated Example

.one .one-contents, 
.two .two-contents { 
    height: inherit; 
} 

当然,你也可以设置高度为0,但inherit值可能更灵活。

如果元素包含多个子元素,那么你总是带有普遍性选择,*结合直接子选择器,>,中联,以针对任何直接的子元素(而不是所有嵌套子元素)。

.one > *, 
.two > * { 
    height: inherit; 
} 

如果想要另一个解决方案,另一种是将父元素的display值更改为flex,或在这种情况下,inline-flex

Updated Example

.one, .two { 
    display: inline-flex; 
} 
+0

我明白了,谢谢。这两个答案都可以解决这个问题,但我可能会选择这个答案,因为它适合我当前的实施。 – shell

1

我相信你的标记是过于复杂:你应该只使用min-heightmax-height组合为你想要的结果:

.content-box { 
 
    vertical-align: top; 
 
    display: inline-block; 
 
    min-height: calc(.5625 * 200px); 
 
    max-height: calc(.5625 * 200px); 
 
    width: 200px; 
 
    background-color: white; 
 
    overflow-y: auto; 
 
    margin: 0 15px 15px 0; 
 
    
 
    /* rest are totally optional*/ 
 
    padding: 10px; 
 
    box-sizing: border-box; 
 
} 
 
body { 
 
    background-color: #eee; 
 
    padding: 15px; 
 
}
<div class="content-box"> 
 
    contents for div one 
 
</div> 
 

 
<div class="content-box"> 
 
    contents for div two 
 
    scrollbar not needed here but it appears anyway 
 
    this should probably have a lot more text. a lot more text a lot more text 
 
    this should probably have a lot more text. a lot more text a lot more text 
 
    this should probably have a lot more text. a lot more text a lot more text 
 
</div> 
 

 
<div class="content-box"> 
 
    contents for moar divs 
 
    scrollbar not needed here but it appears anyway 
 
</div>

0

https://jsfiddle.net/m88stpf4/4/

滚动条被添加,因为在我的例子中,高度设置为0。检查小提琴。 我在代码中添加了以下几行代码。

.two { 
    position: relative; 
} 
.two-contents{ 
    position: absolute; 
    top: 0; 
    left: 0; 
} 

这就是使用这种填充顶部(或底部)时,要走的路...让该容器相对,然后添加一个绝对的容器到一个与填充

相关问题