相对父DIV继承了绝对子DIV的宽度 [英] Relative parent DIV to inherit the width of absolute child DIV

查看:387
本文介绍了相对父DIV继承了绝对子DIV的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在父DIV的底部放置一个DIV子元素,但我也希望子DIV的内容帮助指定父DIV的尺寸。



这里是我的HTML / CSS代码示例:

/ p>

// HTML代码:

 < div id =parent > 
< h3>顶部对齐的标题< / h3>
< div id =child>< / div>
< / div>

// CSS代码:

  #parent {
background-color:#222;
position:relative;
height:500px;
}
#child {
background-color:#444;
position:absolute;
bottom:0px;
width:100px;
height:200px;
}

我需要做什么来实现我想要做什么?我可以放弃绝对/相对的CSS规则,并简单地在父DIV中创建一个表,这将允许我实现底部对齐和内容,指示父的维度。



但是,我想知道是否有办法在CSS中做这个,而不必设置父DIV的宽度。

$ b

解决方案

简短的回答是,你所要求的基本上可以'不能使用纯CSS / HTML。 (至少没有表格)你需要读取#child's width / height的Javascript,然后进行你想做的计算(我不知道),并将新的高度/宽度设置为#parent。



否则,如果你想要#child的height / width根据内容改变,当然这是本地CSS,只要将它的height / width设置为auto,然后开始添加文字里面,你会看到它将开始增长,以适应你的内容。



由于#child位于绝对位置,因此它取自文档的正常流程,因此不会影响#parent。


I am trying to position a child DIV at the bottom of a parent DIV, but I would also like the contents of the child DIV to help dictate the dimensions of the parent DIV. As I have it right now, the child DIV doesn't affect the width/height of the parent DIV.

Here is a sample of my HTML/CSS code:

//HTML code:

<div id="parent">
    <h3>Top Aligned Title</h3>
    <div id="child"></div>
</div>

//CSS code:

#parent {
    background-color:#222;
    position: relative;
    height: 500px;
}
#child {
    background-color:#444;
    position: absolute;
    bottom: 0px;
    width: 100px;
    height: 200px;
}

What do I need to do it achieve what I am trying to do? I could forgo the absolute/relative CSS rules and simply create a table within the parent DIV which would allow me to achieve both bottom alignment and content that dictates the parent's dimensions.

However, I'd like to know if there a way to do this in CSS and without having to set the width of the parent DIV.

thanks in advance!

解决方案

The short answer is that what you are asking basically can't be done with pure CSS / HTML. (at least without tables) You'd need Javascript that would read #child's width/height and then do the calculation you want to do (I don't know) and set a new height/width to #parent.

Otherwise, if you mean that you want #child's height/width to change according to its content, of course this is native CSS, just set it's height/width to auto and then start adding text inside it you'll see it will start growing to fit your content inside.

As the #child is positioned absolute, then it is taken OUT of the normal flow of the document, therefore it will not affect the #parent.

这篇关于相对父DIV继承了绝对子DIV的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆