我有一个 item
在容器中有 position: absolute
。我通过 left: 50%
和 transform: translateX(-50%);
将其居中。这个 item
只包含文本,我希望它覆盖它的内容并且文本将尽可能多地换行。
正如我们在下面的代码片段中看到的,item
有足够的空间,但没有增加宽度。它断线了。我知道我可以添加 white-space: nowrap
来阻止它换行,但是如果文本较长,一行不能换行所有文本。
将 width: 100%
添加到 item
无济于事,因为我希望 item
的宽度基于其内容是动态的。
.container {
width: 300px;
height: 200px;
border: solid 1px #123;
position: absolute;
}
.item {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
background-color: #303030;
color: #FFF;
border-radius: 20px;
padding: 8px 16px;
}
<div class="container">
<div class="item">
<span>Hello. Its me. How are you?</span>
</div>
</div>
最佳答案
这就是你想要的吗?使用 left: 0, right: 0
而不是将其居中,然后在 span
中移动其他样式。
.container {
width: 300px;
height: 200px;
border: solid 1px #123;
position: absolute;
}
.item {
position: absolute;
top: 20px;
left: 0;
right: 0;
text-align: center;
}
.item .content {
display: inline-block;
width: auto;
height: auto;
background-color: #303030;
color: #FFF;
border-radius: 20px;
padding: 8px 16px;
}
<div class="container">
<div class="item">
<div class="content">
<span>Hello. Its me. How are you?</span>
</div>
</div>
</div>
关于html - 中心位置 : absolute and make it full size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46235666/