html - 使用 Flexbox 创建适合内容的两列布局

标签 html css flexbox

我有一个两列布局。第 1 列是标题。第 2 列是一个列表。

我希望列适合内容。 (例如,第 1 列应与其内容一样宽)

我还希望列表是水平的。

我想使用 Flexbox,这样我就可以更改列表中的元素并相应地调整布局。

例如所以它看起来像这样:

enter image description here

我该怎么做?

这是我的代码( Codepen is here ):

<div class="wrapper">
<nav class="topics"> 
<span class="unit unit-header">Topics: </span>
<ul id="list" class="list unit">
  <li><a href="#">All</a></li>
  <li><a href="#">Topic 1</a></li>
  <li><a href="#">Topic 2</a></li>
  <li><a href="#">Topic 3</a></li>
  <li><a href="#">Topic 4</a></li>
  <li><a href="#">Topic 5</a></li>
  <li><a href="#">Topic 5</a></li>
  </ul>
</nav>
</div>

.wrapper {
  width: 960px;
  margin: auto;
  padding-top:20px;
}

.topics {
  display: flex;
}

.unit {
  flex: 1 auto;
}

.list {
  display:flex;  
}

.list li {
  flex: 1 auto;
}

如果我添加以下代码,它将起作用:

.unit-header {
  display: table;
  padding-right: 5%;
}

但是,混合表格和 flex-box 对我来说似乎有点老套。有没有更好的办法?

最佳答案

你试过用这个代替吗?

.unit-header {
  flex: 0 1 auto;
}

上述简写属性的意思是:

flex-grow: 0

flex-shrink: 1

flex-basis: auto

关于html - 使用 Flexbox 创建适合内容的两列布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30031671/

相关文章:

javascript - 将输入从 window.open 传递到父页面

javascript - 通过 css/js/html 强制设备方向为横向?

html - IE 10 flexbox 和文本截断

html - angular2 - 使用 flexbox 设置组件的高度

css - flex 方向 : row - children of same height

javascript - $.ajax 中返回 HTML 的问题

Javascript Uncaught TypeError : $(. ..).dialog 不是函数

html - 在 html 打印上设置 2 个分页符

html - 响应链接

javascript - CSS 类未应用于表格行