html - 中心位置 : absolute and make it full size

标签 html css

我有一个 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/

相关文章:

html - 使用导航栏横向滚动

jquery - 无法拉起 div。为什么这行不通?

javascript - Google map 上未显示带有信息窗口的多个标记

java - jsp中如何对从数据库获取的数据添加分页

jquery - 如何使用 JQuery 更改悬停复选框上的 CSS 样式

html - CSS 居中对齐

html - 表达式 Web 4 格式代码快捷方式?

html - 将按钮放在列表的右下角

django - 多页 django 表单 - slider 或 FormWizard?

Jquery从页面底部向上滑动div