html - 换行时如何使父元素收缩?

标签 html css text width

当子元素文本换行时,如何使 HTML 父元素调整其宽度?我需要使用 javascript 还是可以使用 css 来完成?

下面是一个例子。

ul {
  align-items: stretch;
  justify-content: center;
  background: lightgrey;
  display: flex;
  flex-direction: row;
  height: 80px;
  justify-content: flex-start;
  padding-top: 20px;
  padding-bottom: 20px;
}
li {
  background-color: #303E49;
  display: flex;
  list-style: none;
  margin-right: 0.5em;
}
a {
  color: white;
  text-decoration: none;
  margin: 0.5em 0.5em 0.5em 0.5em;
  border: 1px solid white;
}
Resize this window horizontally to see what I am talking about.

<ul>
  <li>
    <a href="#">HowCanIMakeThisBoxShrink
            WhenTheTextBreaksToANewLine?</a>
  </li>
  <li>
    <a href="#">Text</a>
  </li>
  <li>
    <a href="#">Text</a>
  </li>
</ul>

我需要容器元素 <li></li>宽度以匹配其子项的文本宽度 <a></a> .在我当前的实现中,<a></a> 的宽度减少,当文本换行时,而不是 <li></li> 的宽度

谢谢

最佳答案

你可以

  • 为链接添加一个 overflow-wrap 和 fit-content(不确定你是否希望所有 a-elements 以相同的方式工作,然后去掉额外的 break-class)
  • 从 ul 元素中删除 80px 固定高度(不确定您的应用程序是否接受灵活高度。我不得不删除固定值以使元素在垂直方向上正确扩展

让我知道这种方法是否有帮助:

ul {
  align-items: stretch;
  justify-content: center;
  background: lightgrey;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  padding-top: 20px;
  padding-bottom: 20px;
}

li {
  background-color: #303E49;
  display: flex;
  list-style: none;
  margin-right: 0.5em;
}

a {
  color: white;
  text-decoration: none;
  margin: 0.5em 0.5em 0.5em 0.5em;
  border: 1px solid white;
}

a.break {
  overflow-wrap: anywhere;
  height: fit-content;
}
Resize this window horizontally to see what I am talking about.

<ul>
  <li>
    <a class="break" href="#">HowCanIMakeThisBoxShrink
            WhenTheTextBreaksToANewLine?</a>
  </li>
  <li>
    <a href="#">Text</a>
  </li>
  <li>
    <a href="#">Text</a>
  </li>
</ul>

关于html - 换行时如何使父元素收缩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28635174/

相关文章:

html - WKWebView无法用本地前端加载本地HTML

javascript - 在 react 中设置传递给变量的元素的样式

javascript - 圆形 Div 周围的 Div

excel - 如何使用 Excel 文件中的文本数据列作为 x 轴进行绘图?

c# - 如何将数组的内容写入文本文件? C#

javascript - 根据下拉选择更改单选按钮的值

java - 如何在java中输出格式化的html

javascript - 在一定宽度时停止响应

javascript - 当用户点击 <span> (x) 时,关闭 PHP 中的模式

r - 显示线性模型方程文本的函数