【发布时间】:2023-04-01 22:50:01
【问题描述】:
可能重复:
Make outer div be automaticly the same height as its floating content
我觉得我在这里遗漏了一些非常简单的东西......
我们有一个简单的设置:一个包含子 div 的父 div。 我想:
- 让父级根据子级调整其高度
- 将子元素与父元素的右边缘对齐,而不是默认的左边缘。
使用float:right 将导致父级不再正确调整大小,并且子级将“跳出”父级。
我尝试过使用align: right 和text-align: right,但目前还没有骰子。
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:
关于我可以使用#parent 或.right 进行更改以使child2 正确对齐的任何建议?
编辑
我为此找到的最佳解决方法是在父级上使用display:table。虽然我没有在 IE 中对此进行测试,但它解决了我关心的浏览器中的问题,并避免使用 cmets 中讨论的不直观的overflow:hidden 方法。
更好的是:将孩子的左边距设置为自动。
【问题讨论】: