html - 计算 margin-top 值以占据流体设计中的剩余高度

标签 html css margin fluid-layout

基本上,容器具有流体高度和宽度。请考虑以下事项:

<div class="container">
   <span class="header">Hello!</span>
   <div class="box"></div>
   <div class="box"></div>
</div>

两个 box div 各占 40% 高度,假设我为 span 元素应用 15% 高度,其余 5% 为其 margin -top 值。正如预期的那样,它不会达到 container 高度的 100%,因为 margin-top 据我所知是根据宽度计算的。在这种情况下,如何计算 margin-top 百分比值,以便包括边距在内的所有元素加起来等于 container 的整个高度?这是我的 CSS 代码,在此先感谢。

.container {
    height: 80%;
    width: 80%;
}

.header {
    height: 15%;
    display: inline-block;
    margin-top: 5%;         /*how to calculate this correctly*/   
}

.box {
    height: 40%;
}

最佳答案

我认为你可以通过在 header 上使用 flexbox 和 margin-top:auto 轻松获得你想要的东西:

body,html {
 height:100%;
 margin:0;
}

.container {
  height: 80%;
  width: 80%;
  display:flex;
  flex-direction:column;
  border:1px solid;
  box-sizing:border-box;
}

.header {
  flex:0 0 15%;
  background:red;
  align-self: flex-start; /* To have same visual behavior as inline-block */
  margin-top:auto /* this will do the trick*/
}

.box {
  flex:0 0 40%;
  background:yellow;
}
<div class="container">
  <span class="header">Hello!</span>
  <div class="box">a</div>
  <div class="box">b</div>
</div>

关于html - 计算 margin-top 值以占据流体设计中的剩余高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48613606/

相关文章:

javascript - 如何检测 div 或 body 的变化?

javascript - 表中的树状连接器(HTML/CSS/原型(prototype))

CSS 去除内联元素的外边距

javascript - 从大量选项中选择

HTML Fieldset 内容在 100% 高度溢出(Chrome)

javascript - 我希望我的 Canvas 对象出现在弹出窗口中

html - react-select inputProps 未应用于 AsyncSelect

html - 我可以为 "grid-column"设置动画吗?

HTML CSS 表单 - 如何使表单在​​页面上居中?

html - 如何避免 block 元素之间的垂直边距?