首页 > 解决方案 > 如果内容溢出div中指定的宽度和高度,则水平和垂直滚动条

问题描述

#myleft {
  float: left;
  width: 20%;
  position: relative;
}

#myRight {
  float: left;
  width: 80%;
  position: relative;
}

.displayBox {
  float: left;
  width: 33%;
  position: relative;
  height: 60px;
  overflow: auto;
}
<div>
  <div id="myLeft">
    <h4>Left Content</h4>
  </div>
  <div id="myRight">
    <div class="displayBox">
      <p>Display the first content on BOX 1</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 2. The content might overflow if it exceeds the height of 60px otherwise its perfectly fine.</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 3</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 4 and horizontal scroll bar</p>
    </div>
  </div>
  <div>

myRight div可能有三个或更多div。我希望同一行上的所有 div 不会溢出到水平滚动的下一行。对于内容溢出,我指定了每个 div 的高度为 60px 和 overflow:auto,这给了我垂直滚动条。同样,如果有 3 个以上的 div,我想要水平滚动。

标签: htmlcss

解决方案


而不是使用float,你可以使用display: flex

display: flexblock并排对齐子项(类似于float)。添加flex: 0 0 auto;到这些孩子中会阻止它们包装。

要显示水平滚动条,您可以使用overflow-x: auto;.

.container {
  display: flex;
}

#myLeft {
  width: 20%;
}

#myRight {
  width: 80%;
  display: flex;
  overflow-x: auto;
}

.displayBox {
  width: calc(100% / 3); /* to achieve perfect thirds */
  flex: 0 0 auto;
  height: 60px;
  overflow: auto;
}
<div class="container">
  <div id="myLeft">
    <h4>Left Content</h4>
  </div>
  <div id="myRight">
    <div class="displayBox">
      <p>Display the first content on BOX 1</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 2. The content might overflow if it exceeds the height of 60px otherwise its perfectly fine.</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 3</p>
    </div>
    <div class="displayBox">
      <p>Display the first content on BOX 4 and horizontal scroll bar</p>
    </div>
  </div>
</div>


推荐阅读