根据内容调整列宽

时间:2019-12-26 16:55:14

标签: html css

我正在使用HTML和CSS设计一个简单的网页。我想在页面顶部设计一行,该行应有4个按钮-假设内容为“ A”,“ BB”,“ CCC”,“ DDDD”。我想创建这4个按钮,以使它们的宽度根据内容的长度而不同,即“ A”将很小,但是“ DDDD”将是一个更大的按钮,因为它具有4个字母而不是1个字母。

我可以仅使用HTML和CSS来实现此目的,还是需要学习更多技术?

2 个答案:

答案 0 :(得分:2)

这可以单独使用HTML来完成:

<div class="top-row">
  <button>A</button>
  <button>BB</button>
  <button>CCC</button>
  <button>DDDD</button>
</div>

答案 1 :(得分:0)

您绝对可以使用flexbox做到这一点。例如:

div.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  display: flex; /* This element is a flexbox */
}

a.button {
  background-color: green;
  min-width: 50px;
  text-align: center;
  border: 1px solid white;
}

section {
  display: flex; /* This element is a flexbox */
  flex-direction: row;
  flex-wrap: nowrap;
  background: pink;
}

div.column {
  border: 1px solid grey;
  min-height: 100vh;
}

/* These properties set the column widths within an element that is a flexbox */

.width-1x {
  flex-grow: 1;
}

.width-2x {
  flex-grow: 2;
}

.width-3x {
  flex-grow: 3;
}

.width-4x {
  flex-grow: 4;
}
<div class="header">
  <a href="#" class="button width-1x">A</a>
  <a href="#" class="button width-2x">BB</a>
  <a href="#" class="button width-3x">CCC</a>
  <a href="#" class="button width-4x">DDDD</a>
</div>

<section>
  <div class="column width-1x"></div>
  <div class="column width-2x"></div>
  <div class="column width-3x"></div>
  <div class="column width-4x"></div>
</section>

通过设置每个按钮的CSS flex-grow属性,我们可以决定宽度的比例。

在需要根据列的字符数自动更新列的情况下,也可以通过JavaScript进行操作。