使用CSS缩小元素的高度以匹配其父级

时间:2014-12-12 01:02:28

标签: html css height

我想缩小一个元素的高度以匹配其兄弟的高度;兄弟姐妹的身高是动态的。换句话说,我希望有一个可变高度的元素被迫缩小它的高度,以适应它的父母在孩子不在的时候的高度。

<div class="parent">
    <div class="shrunk_element">
        <span style="color: red;" >If I was really tall I sure wish I could shrink to match the height of my sibling</span>
    </div>
    <div class="sibling" style="width: 60%;">
        <img src="http://dummyimage.com/384x216/000/fff?text=variable+width+consistant+aspect+ratio" style="width: 100%;"/>
    </div>
</div>

这是一个更完整但仍无效的示例http://jsfiddle.net/thisma/k3ngo1mg/3/ 这是一个有效但使用javascript和jQuery http://jsfiddle.net/thisma/k3ngo1mg/5/

的示例

1 个答案:

答案 0 :(得分:1)

您可以将父位置设置为相对,将图像向右推(例如使用边距)并将内容设置为绝对,顶部和底部设置为零。将top和bottom设置为零将拉伸div以适合父级。

http://jsfiddle.net/k3ngo1mg/7/

.parent {position:relative;}

.width_constraint {
    width: 60%;
    margin-left:40%; /* pushing the element to the right */
    display: inline-block;
    max-width: 500px;
}
.ratio_enforcer {
    position: relative;
    width: 100%;
    padding-bottom: 56.25%;
}
.fake_iframe {
    position: absolute;
    width: 100%;
    height: 100%;
    outline: 1px solid red;
}

.matched_content {
    width:39%;
    display: inline-block;
    overflow-y: scroll;
    position:absolute; /* setting the element to absolute */
    top:0px;           /* and setting the height to fit the parent */
    bottom:0px;
    left:0px;
}
div {
    vertical-align: top;
}
相关问题