水平和垂直滚动条(如果内容溢出 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>

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

您可以使用 display: flex 代替使用 float

display: flex block子项并排对齐(类似于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>

最新更新