Possible Duplicate:
Make outer div be automaticly the same height as its floating content可能重复:使外部div自动与其浮动内容的高度相同
I feel like I'm missing something very simple here...
我觉得我在这里错过了很简单的东西......
We have a simple setup: a parent div that contains a child div. I want to:
我们有一个简单的设置:包含子div的父div。我要:
- make the parent resize its height based on the child
- align the child to the right edge of the parent instead of the default left.
让父母根据孩子调整其身高
将子项与父项的右边缘对齐,而不是默认左边。
Using float:right
will cause the parent to no longer resize correctly and the child to 'jump out' of the parent.
使用float:right将导致父级不再正确调整大小并且子级“跳出”父级。
I've tried using align: right
and text-align: right
but so far no dice.
我尝试过使用align:right和text-align:对,但到目前为止还没有骰子。
HTML:
<div id="parent"> <p>parent</p>
<div class="child"> <p>child</p> </div>
<div class="child right"> <p>child2</p> </div>
</div>
CSS:
div{ padding: 15px; margin: 5px; }
p{ padding: 0; margin: 0; }
#parent{
background-color: orange;
width: 500px;
}
.child{
background-color: grey;
height: 200px;
width: 100px;
}
.right{ float: right; } // note: as the commenters suggested I should also be using a float:left on the other child.
Result:
What I want:
Any suggestions on what I could change either with #parent
or .right
to make child2
align to the right properly?
有关我可以使用#parent或.right更改内容以使child2正确对齐的任何建议吗?
EDIT
The best fix I found for this is just using display:table
on the parent. Though I haven't tested this in IE it fixes the issue in the browsers I care for and avoids using the un-intuitive overflow:hidden
method discussed in the comments.
我找到的最好的解决方案是在父级上使用display:table。虽然我没有在IE中测试它,但它解决了我关心的浏览器中的问题,并避免使用不直观的溢出:评论中讨论的隐藏方法。
Even better: set margin-left of the child to auto.
更好的是:将孩子的左边距设置为自动。
1 个解决方案
#1
9
Try floating the contents and adding overflow: hidden
to the parent. It's counter-intuitive but worked for me with a similar issue.
尝试浮动内容并向父级添加overflow:hidden。这是违反直觉的,但对我来说也有类似的问题。
EDIT: Also float the first child to the left.
编辑:也将第一个孩子浮到左边。
#1
9
Try floating the contents and adding overflow: hidden
to the parent. It's counter-intuitive but worked for me with a similar issue.
尝试浮动内容并向父级添加overflow:hidden。这是违反直觉的,但对我来说也有类似的问题。
EDIT: Also float the first child to the left.
编辑:也将第一个孩子浮到左边。