我有一些文本想放在 div
的中间。
<div class="container">
<div class="inner">
<div class="text">
this is some text
</div>
</div>
</div>
我想在这段文字后面放置几张背景图片,所以我将包裹文本的 div
设置为 position:absolute
。
.inner {
position: absolute;
margin-top: 90px;
text-align: center;
width: 300px;
}
我还希望该文本具有填充和背景颜色。
.text {
padding: 10px 20px;
color: #fff;
background-color: #000;
}
但是,文本的背景会拉伸(stretch)容器 div
的整个长度。
有什么方法可以使 .text
居中并将其宽度设置为与文本一样长吗?
目前我能做到的唯一方法是删除 .inner
的宽度并为 .text
手动设置 margin-left
,但我的内容是动态的,所以这不会长期有效。
最佳答案
添加display: inline-block;到内部文本div
例如:
.text {
padding: 5px 5px;
color: #fff;
background-color: grey;
display: inline-block;
}
关于html - CSS:限制位置文本背景的宽度:绝对div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23924840/