HTML,flex,连续两个 div,强制一个 div 的大小更小

标签 html css flexbox

<分区>

主题。

我有两个 div(左和右)。我想使左 div 类似于主 div,并强制右 div 与左 div 具有相同的高度,即使它将包含更多内容(并执行 overflow: hidden)。如果有一种方法可以使用 csshtml 而不使用 js,我将不胜感激。

这是一个小片段,我的标记看起来如何:

.parent {
  display: flex;
  flex-direction: row;
  align-items: stretch;
}

.children-1 {
  width: 66.6%;
  background: green;
}

.children-2 {
  width: 33.4%;
  background: yellow;
}
<div class="parent">
  <div class="children-1">
    <p>My content</p>
  </div>
  
  <div class="children-2">
    <p>a lot of content<p>
    <p>a lot of content</p>
  </div>
</div>

最佳答案

将固定高度应用于容器并在第二个子 DIV 上使用 overflow-y: hidden;:

.parent {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  height: 200px;
}

.children-1 {
  width: 66.6%;
  background: green;
}

.children-2 {
  width: 33.4%;
  background: yellow;
  overflow-y: hidden;
}
<div class="parent">
  <div class="children-1">
    <p>My content</p>
  </div>
  
  <div class="children-2">
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
  </div>
</div>

这是没有固定高度的第二个版本,但 HTML 结构发生了变化:只有一个子项(右边的那个),第一个子项中的内容现在在父项中。它对该子元素使用绝对定位并隐藏子元素的溢出 - 请参阅下面的实际设置:

html,
body {
  margin: 0;
}

.parent {
  position: relative;
  padding: 1em;
  background: green;
  overflow-y: hidden;
}

.children-2 {
  width: 33.4%;
  position: absolute;
  right: 0;
  top: 0;
  background: yellow;
}
<div class="parent">
  <p>My content</p>
  <p>My content</p>

  <div class="children-2">
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
    <p>a lot of content</p>
  </div>

</div>

关于HTML,flex,连续两个 div,强制一个 div 的大小更小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47643440/

相关文章:

html - 在html css中实现不规则矩形图像 mask

jquery - 数据切换禁用里面的标签

javascript - 从 Reactjs 中制作 div 滚动

css - CSS的负边距:好的教程和技巧的网站吗?

html - Flexbox,如何在 400 像素处保持至少 2 列?

html - Flex 页眉、内容、页脚布局

javascript - Wordpress 菜单项不再显示当前页面样式

html - 某些字体不适用于@font-face?

Javascript 显示/隐藏滚动到页面顶部

css - 超出最大宽度的无法点击的内容