右对齐子div而不扩展具有动态宽度的父级

bzu*_*ith 1 html css

我一直无法找到这个.

我有一个以身体为中心的div margin: 0 auto;.它包含多个div.我希望它扩展到它最宽的孩子的宽度width: auto;

问题是我想让一个子div在右边对齐,但是这会将我的父级扩展到100%.如果父母没有固定宽度,我将如何实现这一目标?

jos*_*hnh 5

您可以通过将包装器div设置为inline-blocktext-align: center在其父级上设置(而不是使用margin: 0 auto;)来完成您的操作.这是一个例子:http://jsfiddle.net/joshnh/6Ake5/

这是HTML:

<div class="wrapper">
    <div class="foo"></div>
    <div></div>
    <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)

而CSS:

body {
    text-align: center;
}
div {
    border: 1px solid red; /* To see what is going on */
}
.wrapper {
    display: inline-block;
    text-align: left; /* Resetting the text alignment */
    vertical-align: top; /* Making sure inline-block element align to the top */
    /* Inline-block fix for IE7 and below */
    zoom: 1;
    *display: inline;
}
.wrapper div {
    float: left;
    height: 200px; /* To see what is going on */
    margin: 10px; /* To see what is going on */
    width: 200px; /* To see what is going on */
}
.foo {
    border-color: blue; /* To see what is going on */
    float: right;
}?
Run Code Online (Sandbox Code Playgroud)