When your two containers, .outer
and .inner
, are absolutely positioned, your approach is not only correct but also the only way to achieve the desired outcome when the parent container's width is unspecified.
Your solution adheres closely to the CSS 2.1 specification, making it robust.
For further information, it is recommended to refer to:
http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width
This resource details how the width of an absolutely positioned element is calculated.
In your jsFiddle example, please note that the containing block for the two <div>
's is either the viewport or the root element. You have not specified the vertical placement using the top
or bottom
properties. Additionally, since the absolutely positioned elements are out-of-flow, their intrinsic height does not impact the height calculation of the containing block. In certain scenarios, this factor may render this approach unusable without adjustments.
Furthermore, enclosing your sample code within a relatively positioned wrapper <div>
with a fixed width would still result in correct centering of the child elements, as illustrated in this demo: http://jsfiddle.net/audetwebdesign/aNS5j/ (Ensure the wrapper element has sufficient height.)
If the width of the containing block (viewport or wrapper element in the demo) is less than the width of your child elements (400px in the example), the centering may not function as expected. This behavior aligns with the CSS specification guidelines.
Your query delves into a fundamental aspect of how the CSS visual formatting model operates.
Additional Information
The same effect can be achieved without absolute positioning on the .inner
element, where margin: 0 auto
would suffice. This alternative would result in a slightly more concise CSS declaration.
Regarding Negative Margins
While negative margins tend to work consistently in modern browsers, the CSS 2.1 specification does not prescribe how negative margins should be implemented. In practice, negative margins may encounter issues in user agents strictly adhering to the CSS specification.