首页 > 解决方案 > HTML:CSS:动态显示的 DIV 会影响其他 DIV

问题描述

我有一个小模板,可以大致解释我的问题。

$('#someBtn').on('click', function(){
	$('.notification-panel').toggle();
});
.wrapper {
  height: 100%;
  width: 100%;
}

.notification-panel {
  background: green;
  width: 100%;
  display: none;
}

.content {
  background: yellow;
  width: 100%;
  height: 100px;
  overflow: auto;
}

.footer {
  background: blue;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class='wrapper'>
  <div class='notification-panel'>
    Some notification
  </div>
  <div class='content'>
    Scaling to screen using vh and vw <br>
    Line 2 <br>
    Line 3 <br>
    Line 4 <br>
    Line 5 <br>
    Line 6 <br>
    Line 7 <br>
    Line 8 <br>
    Line 9 <br>
    Line 10 <br>
    Line 11 <br>
    Line 12 <br>
    Line 13 <br>
    Line 14 <br>
    Line 15 <br>
    Line 16 <br>
    Line 17 <br>
    Line 18 <br>
    Line 19 <br>
    Line 20 <br>
    Line 21 <br>
    Line 22 <br>
    Line 23 <br>
    Line 24 <br>
    <button id ="someBtn">
      Click me
    </button>
  </div>
  <div class='footer'>
    Footer
  </div>
</div>

如您所见,我有影响底部元素的动态“通知面板”元素(在切换后它将底部元素向下移动)。我的目标是在没有任何变化的情况下缩小可滚动的“内容”元素的高度。我想 flex (flex-shrink/flex-grow) 应该可以解决这个问题,但我不知道如何将它应用到我的模板中。

UPD1:“通知面板”元素的“位置:固定”不能解决问题。它只是与我的“内容”元素的顶部重叠,但我的目标是缩小“内容”元素的高度。

标签: javascriptjqueryhtmlcssflexbox

解决方案


Flex 会这样做 - 只需让你的包装器 flex 并从你的内容 div 中删除高度并赋予它 flex-grow (不收缩)

$('#someBtn').on('click', function() {
  $('.notification-panel').toggle();
});
html,
body {
  height: 100%;
  margin: 0;
}

.wrapper { /* this is optional - you can apply this directly to the body */
  display:flex;
  flex-direction:column;
  height: 100%;
}

.notification-panel {
  background: green;
  width: 100%;
  display: none;
}

.content {
  flex-grow:1;               /* this makes the content panel fill the remaining space */
  background: yellow;
  overflow: auto;
}

.footer {
  background: blue;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class='wrapper'>
  <div class='notification-panel'>
    Some notification
  </div>
  <div class='content'>
    Scaling to screen using vh and vw <br> Line 2 <br> Line 3 <br> Line 4 <br> Line 5 <br> Line 6 <br> Line 7 <br> Line 8 <br> Line 9 <br> Line 10 <br> Line 11 <br> Line 12 <br> Line 13 <br> Line 14 <br> Line 15 <br> Line 16 <br> Line 17 <br> Line 18
    <br> Line 19 <br> Line 20 <br> Line 21 <br> Line 22 <br> Line 23 <br> Line 24 <br>
    <button id="someBtn">
      Click me
    </button>
  </div>
  <div class='footer'>
    Footer
  </div>
</div>


推荐阅读