gpt4 book ai didi

html - 如何使内联 block 保持在一行但仍适合可用宽度?

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:13 25 4
gpt4 key购买 nike

我有以下演示代码来演示我的问题。我想通过 CSS 在标题旁边添加一些装饰,但遇到了这个问题。如果标题足够短,它会按预期工作,但如果标题较长,当文本环绕但不足以位于 div.base 内时。

如何使第二个样本看起来像下面的第三个(假)样本? enter image description here

需要说明的是,我希望 div 内容显示为“内联”,只有中间的 div 允许自动换行,div 内容应保持在容器宽度内,而不会在 div 之间添加额外的空格。

<html>
<style>
.base { font-size:32pt; text-align:center; border:solid; display: block; white-space:nowrap; width:400px;}
.base span, .base::before, .base::after { display: inline-block; border:solid; white-space:normal;}
.base::before { content: "\00a0-\00a0"; }
.base::after { content: "\00a0-\00a0"; }
</style>
<body>
<div class="base">
<span>Short text</span>
</div>
<div class="base">
<span>Testing some longer text</span>
</div>
<div class="base">
<span>Fake some <br>longer text</span>
</div>
</body>
</html>

最佳答案

两种方法,第二种更好(flex),但取决于浏览器支持:

1.) 您可以在该跨度上使用带有百分比或(更好的)calc 值的 max-width:

.base {
font-size: 32pt;
text-align: center;
border: solid;
display: block;
white-space: nowrap;
width: 400px;
}

.base span,
.base::before,
.base::after {
display: inline-block;
border: solid;
white-space: normal;
}

.base::before {
content: "\00a0-\00a0";
}

.base::after {
content: "\00a0-\00a0";
}
.x2 span {
max-width: calc(100% - 112px);
}
<div class="base x1">
<span>Short text</span>
</div>
<div class="base x2">
<span>Testing some longer text</span>
</div>
<div class="base x3">
<span>Fake some <br>longer text</span>
</div>

2.) 这是使用 flexbox 的第二种解决方案:

.base {
font-size: 32pt;
text-align: center;
border: solid;
display: block;
white-space: nowrap;
width: 400px;
display: flex;
justify-content: center;
}

base span {
}

.base span,
.base::before,
.base::after {
display: inline-block;
border: solid;
white-space: normal;
}

.base::before {
content: "\00a0-\00a0";
margin-right: 10px;
}

.base::after {
content: "\00a0-\00a0";
margin-left: 10px;
}
<div class="base x1">
<span>Short text</span>
</div>
<div class="base x2">
<span>Testing some longer text</span>
</div>
<div class="base x3">
<span>Fake some <br>longer text</span>
</div>

关于html - 如何使内联 block 保持在一行但仍适合可用宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43618856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com