在父div中对齐Child Div

Joh*_*nes 11 html css parent alignment

可能重复:
使外部div自动与其浮动内容的高度相同

我觉得我在这里错过了很简单的东西......

我们有一个简单的设置:包含子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>
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

结果:

结果

我想要的:

我想要的是

什么我可以要么改变任何建议#parent.right作出child2右对齐正确?

编辑

我找到的最好的解决方法就是display:table在父级上使用.虽然我没有在IE中测试它,但它解决了我关心的浏览器中的问题,并避免使用overflow:hidden评论中讨论的非直观方法.

更好的是:将孩子的左边距设置为自动.

Kai*_*aja 9

尝试浮动内容并添加overflow: hidden到父级.这是违反直觉的,但对我来说也有类似的问题.

编辑:也将第一个孩子漂浮到左边.