CSS - 相对于父容器大小的空着色容器

时间:2017-03-04 12:26:50

标签: javascript html css

我的网页上有一个标题,根据视口(例如15vh)更改高度,最小高度为50px。

我想在此标题中创建一个彩色方块,无论用户的视口如何,该方块始终都是标题高度的50%。彩色框中没有内容。它仅用于样式目的。我知道我不能使用身高:15%;因为容器中没有内容,因此不会显示任何内容。我无法根据视口单位定义框,因为标题并不总是视口高度的15%(由于最小高度分配)。

有没有办法用CSS完成这个?

这是我的设置:

html,
body {
  padding: 0;
  margin: 0;
}

img {
  max-width: 100%;
  height: auto;
}

.header {
  position: relative;
  background-color: grey;
  border-bottom: 1px solid #CCC;
  min-height: 50px;
}

.responsivecontainer {
  float: left;
  max-width: 20vw;
  min-height: 50px;
  display: flex;
}

.logo {
  margin: auto 0;
}

.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

.box {
  float: left;
  height: 50%;
  background-color: black;
}

.clearfix {
  display: inline-block;
}


/* Hides from IE-mac \*/

* html .clearfix {
  height: 1%;
}

.clearfix {
  display: block;
}


/* End hide from IE-mac */


/* @end */
<div class="header clearfix">

  <div class="responsivecontainer">
    <div class="logo">
      <img src="http://www.bluebean.ca/logo1.jpg">
    </div>

  </div>

  <div class="box">
    <img src="http://www.bluebean.ca/grey.jpg">
  </div>

</div>

1 个答案:

答案 0 :(得分:0)

你可以用绝对定位来做到这一点。像这样:

&#13;
&#13;
html,
body {
  padding: 0;
  margin: 0;
}

img {
  max-width: 100%;
  height: auto;
}

.header {
  position: relative;
  background-color: grey;
  border-bottom: 1px solid #CCC;
  min-height: 50px;
  position: relative;
}

.responsivecontainer {
  float: left;
  max-width: 20vw;
  min-height: 50px;
  display: flex;
}

.logo {
  margin: auto 0;
  z-index:10;
}

.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

.box {
  position:absolute;
  top:0;
  left:0;
  height: 50%;
  background-color: black;
  width: 100%;
}
&#13;
<div class="header clearfix">
  <div class="box"></div>
  <div class="responsivecontainer">
    <div class="logo">
      <img src="http://www.bluebean.ca/logo1.jpg">
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

您还需要将z-index值设置为大于框的值,以将框保留在标题中的元素下方。