当子元素文本换行时,如何使 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/