[英]how to set div width relative to content on ignoring parent's width
我正在寻找一种方法来基于包围的内容设置div宽度,而不是继承父母的宽度,例如:
<div id="parent" style="width:100px">
<div id="child"> <!-- i want to add css to this div -->
<p style="width:200px;"> this s atext</p>
<img src="this s an image" style="width:300px;">
</div>
</div>
我想要的是自动将#child
宽度设置为500px,我不想手动设置#child
的宽度,因为在我的实际情况下,我不知道其内容的宽度,(有关以下内容的更多详细信息,请查看下面的评论)我的情况)
请注意,以下所有解决方案均不适用于我:
display:inline;
width:auto;
overflow:visible;
你能帮我吗?
这是一种适用于您的布局的方法。
如果HTML如下所示:
<div id="parent" style="width:100px">
<div id="child"> <!-- i want to add css to this div -->
<p style="width:200px;">this is text</p>
<img src="http://placekitten.com/600/400" style="width:300px;">
</div>
</div>
应用以下CSS :
#parent {
border: 1px dashed blue;
}
#child {
background-color: beige;
white-space: nowrap;
}
#child p {
border: 1px dotted blue;
display: inline-block;
vertical-align: top;
margin: 0;
}
#child img {
border: 1px dotted blue;
vertical-align: top;
}
边框仅用于说明,以说明各个框的边缘如何。
看起来您希望两个子元素p
和img
在同一行上,因此总宽度为500px(200px + 300px)。
首先,将display: inline-block
应用于p
以便它可以与图像内联。
要将p
和img
保持在一行上,可以将white-space: nowrap
#child
包含#child
的块。
另外,您可以确保两个元素之间没有空格(例如,换行符),但是如果内容来自CMS或其他某种提要,则可能不可行。
请注意, #child
元素占据#parent
块的宽度,并且后代元素相应地溢出。 这可能不理想,但可以根据需要进行修复。
您可能需要根据实际内容将最大宽度设置为#child
。
参见演示: http : //jsfiddle.net/audetwebdesign/c94Ya/
在Firefox中,结果如下所示:
可以为子div设置宽度500px。 但它不占用宽度,因为父容器的宽度为100px。
如果要为子div设置500px,则意味着将父div的样式更改为500px或大于500px,此时只有子div起作用。
例如
<div id="parent" style="width:100%">
<div id="child" style="width:500px"> <!-- i want to add css to this div -->
<p style="width:200px;"> this s atext</p>
<img src="this s an image" style="width:300px;">
</div>
</div>
在此示例中,我将父CSS宽度100px更改为100%
尝试通过在CSS中使用z-index
来使ID分开。 它用于将对象放在彼此之上,而不受彼此影响
#child {
width: 500px;
z-index: 100;
}
从这里开始,任何z-index
大于100的ID都将在子ID之上。 并且将z-index
设置为低于100的ID设置在子ID的下方。
当我尝试此操作时,红色边框比黑色边框宽
<div id="parent" style="width:100px;border: 1px solid black">
<div id="child" style="width:500px;border: 1px solid red"> <!-- i want to add css to this div -->
<p style="width:200px;"> this s atext</p>
</div>
</div>
这是你想要的?
<div id="parent" style="width:200px; background: red; height: 400px">
<div id="child" style="background: yellow; width: 500px;">
<p> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, </p>
<img src="this s an image" style="width:100px" />
</div>
</div>
更新: http : //jsfiddle.net/A9xDG/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.