html - 使用滚动条在容器中水平对齐 div

标签 html css flexbox

我试图在容器 div 中将几个 div 元素彼此相邻对齐。容器应该有一个水平滚动条。

enter image description here

我尝试过不同的解决方案,但每个解决方案都有不同的问题。请注意,我正在寻找“通用”解决方案。 这意味着它应该与

  • 任何容器高度
  • 任意数量的 child (宽度可以不同)

1.

display: inline-block; 

问题:当 div 没有“相似”内容时,它们没有正确对齐。

jsfiddle:https://jsfiddle.net/k08m6y6e/

2.

float: left;

问题:盒子换行 - 没有滚动条

jsfiddle:https://jsfiddle.net/k08m6y6e/1/

3.

display: table-cell; 

问题:没有滚动条 - 这实际上对我来说很有意义,但这意味着这不能解决我的问题

jsfiddle:https://jsfiddle.net/k08m6y6e/5/

  1. flex 盒子; 问题: child 的最小宽度被忽略而且在浏览器之间似乎不一致(尤其是 IE)

谁能帮我想出一个好的解决方案?

--

解决方案

此处提供的两个答案(来自 Michael 和 Andrei)都非常有效;非常感谢。可惜我只能接受一个。

小提示:Internet Explorer 似乎对这两种解决方案都有问题。滚动条覆盖了 child 的内容和/或 child 底部的一小部分被切断了。 Chrome 和 Firefox 按预期工作。

最佳答案

通过 inline-block,您可以使用 vertical-align 来对齐 div。

#container {
  height:150px;
  width:400px;
  overflow-y:hidden;
  overflow-x:auto;
  white-space: nowrap;
}

.hdiv {
  border:solid 1px black;
  height:100%;
  min-width:100px;
  display:inline-block;
  vertical-align: top;
}
<div id="container">
  <div class="hdiv">
    Text
  </div>
  <div class="hdiv">
    Line 1 <br/>
    Line 2
  </div>
  <div class="hdiv">
    <img src="https://www.google.at//images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="g" style="height:100px" />
  </div>
</div>

由于要垂直对齐每个单元格中的内容,可以使用inline-flex代替inline-block,并使用align-items: center 垂直居中。我还添加了 justify-content: center 以水平居中。

#container {
  height:150px;
  width:400px;
  overflow-y:hidden;
  overflow-x:auto;
  white-space: nowrap;
}

.hdiv {
  border:solid 1px black;
  height:100%;
  min-width:100px;
  display:inline-flex;
  vertical-align: top;
  justify-content: center;
  align-items: center;
}
<div id="container">
  <div class="hdiv">
    Text
  </div>
  <div class="hdiv">
    Line 1 <br/>
    Line 2
  </div>
  <div class="hdiv">
    <img src="https://www.google.at//images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="g" style="height:100px" />
  </div>
</div>

关于html - 使用滚动条在容器中水平对齐 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43297407/

相关文章:

jquery - 如何将 anchor 标记添加到列表中的文本

html - 如何进行输入以占用 flex 容器中的所有剩余宽度?

html - 如何删除组织模式 html 导出中的页脚详细信息?

html - CSS 定义在页面中分隔

javascript - 如何在悬停另一个 HTML 元素时创建平滑缩放并显示叠加层?

html - 简单的横幅广告 - 是否有更好的桌面和移动布局方式? ( flex 盒/CSS 网格)

css - 使 div 子级在 100% 高度父级 div 内可滚动

html - 部分背景上的视频不是全尺寸

css - 为什么 Chrome 会针对出现在错误位置的文本输入字段弹出错误消息?

css - 在 :host declaration of a Custom Element 中使用 CSS 计数器重置