简体   繁体   English

绝对定位的div的宽度

[英]Width of an absolutely positioned div

I have following HTML : 我有以下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>

And this CSS : 而这个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;
}

And here is the Demo . 这是演示

The inner div should take its text content width upto 400px maximum (should be fluid). 内部div的文字内容宽度最大应为400px (应该是可变的)。 With this code it takes its parent's width. 使用此代码,它将占用其父对象的宽度。

How do achieve this? 如何做到这一点?

UPDATE UPDATE

This inner div text can be changed dynamically 此内部div文本可以动态更改

When using max-width put explicit width first 使用max-width宽度时,请先放置显式宽度

 .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; } 
 <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> 

Actually, an element with absolute positioning doesn't take any width by default, only the size of its content . 实际上, 具有绝对定位的元素默认情况下不会采用任何宽度,而只是其内容的大小

So, if a block element should have a 100% width as default, you have to set it for an element with position absolute . 因此,如果块元素默认应具有100%的宽度,则必须为position absolute的元素设置它。

I'm not sure what you are trying to achieve there, but you should simply set the width property you "lost" with position absolute : 我不确定您要达到的目标,但您应该简单地将“丢失”的width属性设置为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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM