【问题标题】:Set height of element to height of element with % height将元素的高度设置为具有 % 高度的元素的高度
【发布时间】:2017-03-23 13:03:05
【问题描述】:

我想将元素聊天框的高度设置为元素视频框的高度。但我不知道该怎么做。如果你给我一个不使用 JavaScript 的方法,我也很好。

代码:

#content {
  width: 80%;
  max-width: 1300px;
  min-width: 900px;
  margin: 80px auto;
}
#stream {
  position: relative;
  padding-bottom: 56.25%;
  height: 0;
  overflow: hidden;
  width: 100%;
  height: auto;
  display: flex;
}
#video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div id="content">
  <div style="width:75%;display:inline-block;vertical-align:top;" id="videobox">
    <div id="stream">
      <iframe id="video" src="http://player.twitch.tv/?channel=marmeladenoma" height="720" width="1280" frameborder="0" scrolling="no" allowfullscreen="true">
      </iframe>
    </div>
  </div>
  <div style="width:25%;float:right;display:inline-block;background-color:rgb(3, 40, 74)" id="chatbox">
    hi
  </div>
</div>

【问题讨论】:

    标签: html css flexbox height css-position


    【解决方案1】:

    如果您不知道 videobox 的高度(因为它是可变的)并且无法在 CSS 中显式设置它,则必须使用 JavaScript 通过获取 videobox 的高度并设置chatbox 相同。这是一个使用 jQuery 的简单示例:

    window.onload = function() {
      var h = $('#videobox').outerHeight();
      $('#chatbox').css('height', h);
    };
    

    http://codepen.io/paulcredmond/pen/WoQdPz

    否则,您可以使用 flexboxstretch 来帮助您。见:

    https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    【讨论】:

      【解决方案2】:

      如果您可以将两个元素放在同一个父 div 中。

      然后您可以设置包含 div 的高度并在两个元素上使用 height:100%。

      如果不能将它们放在同一个 div 中,则必须使用 javascript 或将两个元素的高度设置为精确的像素数。

      【讨论】:

        【解决方案3】:

        只需将#contentdisplay 设置为flex,然后将#chatboxheight 设置为inherit。那就是:

        #content {
            display: flex;
            ...
        }
        
        #chatbox {
            height: inherit;
            ...
        }
        

        因此,完整的样式规则是:

        #content {
            display: flex;
            width: 80%;
            max-width: 1300px;
            min-width: 900px;
            margin: 80px auto;
        }
        #stream {
            position: relative;
            padding-bottom: 56.25%;
            height: 0;
            overflow: hidden;
            width: 100%;
            height: auto;
            display: flex;
        }
        #video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
        #chatbox {
            height: inherit;
        }
        

        【讨论】:

          猜你喜欢
          • 2021-10-24
          • 2017-04-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-04
          • 2019-01-18
          • 2016-03-17
          • 2012-05-14
          相关资源
          最近更新 更多