CSS:限制文本背景的宽度位置:绝对div?

时间:2014-05-29 02:32:10

标签: html css

我有一些文字,我想在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;
}

但是,文本的背景会延伸容器div的整个长度 有没有办法使.text居中并将其宽度设置为与文本一样长?

我目前唯一能做的就是删除.inner的宽度,并为margin-left手动设置.text,但我的内容是动态的,所以这不起作用从长远来看。

JSFiddle here

5 个答案:

答案 0 :(得分:2)

display:inline-block; 添加到内部文本div

例如:

.text {
    padding: 5px 5px;
    color: #fff;
    background-color: grey;
    display: inline-block;
}

enter image description here

http://fiddle.jshell.net/R7ah9/

答案 1 :(得分:0)

如果你添加display:inline;对.text风格,你会得到你想要的。

答案 2 :(得分:0)

http://fiddle.jshell.net/3Ahs2/1/

您需要样式文字对齐中心

答案 3 :(得分:0)

测试此代码:

 .container {
      background-color: #FD5361;
      border: 1px solid #FF0000;
      height: 39px;
      position: relative;
      width: 200px;
     }
   .inner {
        display: inline-block;
        opacity: 0.1;
        position: absolute;
        text-align: center;
        top: 0;
        width: 300px;
     }
    .text {
       background-color: #000000;
       color: #FFFFFF;
        padding: 10px 20px;
     }
    //such as background-position

答案 4 :(得分:0)

您的height属性缺少冒号,我删除了可能不必要的.inner元素。

这是小提琴:http://jsfiddle.net/3Ahs2/5/