绝对定位的div的宽度

时间:2015-08-21 05:46:36

标签: html css css-position

我关注HTML

<div class="outter">
    <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id quis animi nulla accusantium minus, similique quos ullam consectetur neque voluptatibus odio, ipsam cumque consequuntur dolorem harum nostrum sequi dolores! Ut.</div>
</div>

这是CSS

.outter {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: red;
    margin-top: 200px;
    margin-left: 100px;    
    position: relative;
}
.inner {
    position: absolute;
    top: -60px;
    left: -100px;
    background: green;
    display: inline-block;
    max-width: 400px;
}

这是Demo

内部div应将其文字内容宽度设置为最大400px(应该是流畅的)。使用此代码,它将采用其父宽度。

如何实现这一目标?

更新

此内部div文本可以动态更改

2 个答案:

答案 0 :(得分:0)

使用max-width时将显式宽度放在第一位

&#13;
&#13;
.outter {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: red;
    margin-top: 200px;
    margin-left: 100px;
    position: relative;
    min-width: 100px;
}
.inner {
    position: absolute;
    top: -60px;
    left: -100px;
    background: rgba(0, 255, 0, .5);
    display: inline-block;
    width: 400px;
    max-width: 400px;
}
&#13;
<div class="outter">
    <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id quis animi nulla accusantium minus, similique quos ullam consectetur neque voluptatibus odio, ipsam cumque consequuntur dolorem harum nostrum sequi dolores! Ut.</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

实际上,具有绝对定位的元素默认不占用任何宽度,只占其内容的大小

因此,如果块元素的默认宽度应为100%,则必须为具有position absolute的元素设置它。

我不确定你想要在那里实现什么,但是你应该只用绝对位置设置你“丢失”的宽度属性:

.inner {
    position: absolute; // here, width becomes "auto"
    top: -60px;
    left: -100px;
    background: rgba(0, 255, 0, .5);
    display: inline-block;
    width: 100%; // 100% = closest relative parent width, set it to whatever you want
    max-width: 400px;
}