中心位置:绝对并使其全尺寸

时间:2017-09-15 09:00:05

标签: html css

我在容器中有itemposition: absolute。我将其集中在left: 50%transform: translateX(-50%);。这个item只包含文字,我希望覆盖它的内容,文字尽可能地覆盖

正如我们在下面的snipet中看到的那样,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>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:3)

这是你想要的吗?请使用left: 0, right: 0将其居中,然后在span中移动其他样式。

&#13;
&#13;
.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;
}
&#13;
<div class="container">
  <div class="item">
    <div class="content">
      <span>Hello. Its me. How are you?</span>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

flexbox会为你工作吗?

&#13;
&#13;
.container {
  width: 300px;
  height: 200px;
  border: solid 1px #123;
  display: flex;
  justify-content: center;
  align-items: center;
}

.item {
  background-color: #303030;
  color: #FFF;
  border-radius: 20px;
  padding: 8px 16px;
}
&#13;
<div class="container">
  <div class="item">
    <span>Hello. Its me. How are you? Hello. Its me. How are you? Hello. Its me. How are you? </span>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

请试一试。

.container {
  width: 300px;
  height: 200px;
  border: solid 1px #123;
  position: relative;
}
.item {   
 margin-top: 20px;
 display: flex;
 justify-content: center;
}
.item span{
  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>

答案 3 :(得分:0)

尝试为span代码添加中心对齐

.container {
  width: 300px;
  height: 200px;
  border: solid 1px #123;
  position: absolute;
}

.item {
  position: absolute;
  top: 20px;
  left: 0;
  right: 0;
  width: auto;
  text-align: center;
}

.item .itemInner {
  background-color: #303030;
  color: #FFF;
  border-radius: 20px;
  padding: 8px 16px;
  text-align: left;
  margin: 0 auto;
}
<html>

<head>
</head>

<body>
  <div class="container">
    <div class="item">
      <span class="itemInner">Hello. Its me.</span>
    </div>
  </div>
</body>

</html>