2017-10-11 113 views
0

请参阅this Fiddlediv的样式高度与图像填充父母的高度

我有一个顶级div,其高度配置为一个屏幕高度(height:100vh)。在这个div中,有一个固定高度(60px)的子div和另一个子div,我想要填充剩余的高度(以便响应不同的屏幕尺寸)。

这个孩子div有一个图像和一些文本。目前,它的宽度是硬编码的,否则图像填满了整个屏幕(并且超过了其父节点的长度)。设置height:100%(或甚至calc(100% - 60px))不会像我希望的那样扩展div。

.one-page { 
 
    min-height: 100vh; 
 
    max-height: 100vh; 
 
    background-color: #FF5555; 
 
} 
 

 
.fixed-size { 
 
    height: 60px; 
 
    border-style: solid; 
 
} 
 

 
.main-container { 
 
    background-color: #55FF55; 
 
    width: 300px; 
 
    margin: auto; 
 
} 
 

 
.subtitle { 
 
    text-align: center 
 
} 
 

 
.other { 
 
    background-color: blue; 
 
} 
 

 
img { 
 
    vertical-align: middle; 
 
    width: 100%; 
 
    height: auto; 
 
}
<body> 
 
    <div class="one-page"> 
 
    <div class="fixed-size"> 
 
     this div is a fixed size 
 
    </div> 
 
    <div class="main-container"> 
 
     <p> 
 
     <img src="http://images.clipartpanda.com/square-clip-art-clipart-square-shield-256x256-e296.png"> 
 
     </p> 
 
     <div class="subtitle"> 
 
     subtitle text 
 
     </div> 
 
    </div> 
 
    </div> 
 
    <div class="other"> 
 
    something else 
 
    </div> 
 
</body>

回答

0

尝试使用height:calc(100vh - 60px)

.main-container { 
    background-color: #ff00ff; 
    width: 300px; 
    margin: auto; 
    padding:0; 
    height:calc(100vh - 60px); 
    } 

DEMO

0

使用Flexbox的去解决它。运行下面的代码片段,你就会明白。 flex-grow: 1基本上会给所有剩下的高度给第二个孩子。

.p { 
 
    height: 100vh; 
 
    display: flex; 
 
    flex-direction: column; 
 
} 
 

 
.c1 { 
 
    height: 60px; 
 
    background-color: green; 
 
} 
 

 
.c2 { 
 
    flex-grow: 1; 
 
    background-color: red; 
 
}
<div class="p"> 
 
    <div class="c1"></div> 
 
    <div class="c2"></div> 
 
</div>

+0

这似乎是相当接近我要找的,但是当我添加图像,它仍然存在问题。我试图根据可用的垂直空间调整图像大小,但在此解决方案中它保持不变。看起来我必须指定一个宽度来改变它,但我希望根据高度来计算宽度。 – MattDs17

+0

结帐此链接:https://stackoverflow.com/questions/1891857/how-do-you-stretch-an-image-to-fill-a-div-while-keeping-the-images-aspect-rat –