Is this an acceptable method for aligning absolutely-positioned elements in the center horizontally?

Looking for a way to horizontally center fixed-width elements within their containers without using negative pixel margins? I've found a solution that seems to work well:

http://jsfiddle.net/aaronadams/Mquha/

<div class="outer center">
    <div class="inner center"></div>
</div>
.outer {
    position: absolute;
    width: 400px; height: 400px;
    background: #999;
}

.inner {
    position: absolute;
    width: 200px; height: 400px;
    background: #666;
}

.center {
    left: 0; right: 0;
    margin-left: auto; margin-right: auto;
}

While this solution seems to work across different browsers, it might be considered a positioning hack that could potentially cause issues. Is this method reliable for production, or should it be avoided?

Answer №1

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.

Answer №2

When it comes to CSS, the decision to use position:absolute; can sometimes feel like giving up on a more elegant solution. However, there are cases where absolute positioning is the only viable option.

In the industry, the standard solution is often to use negative margins, as demonstrated in this example: http://jsfiddle.net/Mquha/3/

Despite this, the negative margin approach can feel messy and lacks reusability.

After exploring the method you suggested, it appears to be a more modern and surprisingly effective discovery. It offers a cleaner alternative to negative margins and is widely supported among major browsers, as you mentioned. I plan to adopt your suggested approach in future projects, as it provides a cleaner solution for absolute positioning. I recommend others to do the same.

Answer №3

This is my top choice

Update your CSS with the following:

#outer {
    position: absolute;
    width: 400px; height: 400px;
    background: #999;
}

#inner {
    position: absolute;
    width: 200px; height: 400px;
    background: #666;
}

.center {
    margin-left: auto; margin-right: auto;
}

Also, modify your HTML to:

<div id="outer center" class="center">
    <div id="inner center" class="center"></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Beginner in CSS wanting to set background image for input field

I am working on incorporating icons into my project. The image I have contains an array of 16x16 icons at this URL: "http://www.freepbx.org/v3/browser/trunk/assets/css/jquery/vader/images/ui-icons_cd0a0a_256x240.png?rev=1" Does anyone know how I can selec ...

Adjusting my menu layout causes my header image to be partially covered

I've been trying to make my menu fixed at the top of my website, but it keeps overlapping into my header image and doesn't look right. I've experimented with different solutions, but nothing seems to work. Here's the CSS code I used th ...

Is it possible to create a basic textarea with minimal height-rows but fill 100% of the height?

Within my div, there is a textarea element that I am having trouble sizing correctly vertically. The container div is set to the right size (100%), but I need to give the textarea a minimum height or number of rows to enable scrolling if needed, while sti ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

Horizontal expanding and collapsing navigation menu

Is there a way to modify the expand menu bar so it expands from left to right or right to left, instead of top down? Any assistance would be greatly appreciated. Existing Expand Menu Bar <HTML> <HEAD> <META http-equiv="Content-Type" c ...

Issue with displaying Bootstrap Tooltip

Recently, I launched a fresh website (currently residing on a sub-domain). However, I am facing an issue with the tooltip not showing up when hovering over the text Get the FinEco Bookmarklet. <span class="bookmarklet"><span class="fa fa-bookmark ...

Having trouble enlarging the navigation panel

I am working on creating a dynamic navigation bar with bootstrap 4. However, I am facing an issue with the top right button not expanding the navigation bar as expected. I have checked my code but I cannot figure out what I missed. Can anyone help me with ...

Is there a way to display these panels in a scrollable table layout?

My aim is to replicate this specific styling: https://i.stack.imgur.com/jz5lm.png This type of table shown above is being dynamically imported via Redux: class LocationList extends React.Component { componentDidMount() { this.props.fetchLocations( ...

Unable to make a div grow within a Popper component in a React.js application

I'm facing a challenge with implementing a CSS feature and need some assistance. https://i.stack.imgur.com/KXpGd.png Upon clicking the "See link options" button, the content loads but spills out of the popper. My goal is to have the popper expand in ...

Adjusting the Image Width in React to Match Bootstrap Column Width

Exploring the capabilities of the react-image-mapper library, I stumbled upon an interesting feature: the ImageMapper component offers a prop called width, representing the image width in pixels. Integrating this component into my application based on the ...

Tips for creating a div element that closes on the second click:

On the PC version, I have three blocks that open and close perfectly when clicked. However, on the mobile version, when I click on one block, it opens but does not close unless I click on another block. Additionally, if I click again on the same block th ...

Set the height of the main div container to a fixed size

I am facing an issue with my div container (mapInfo-Container) which contains multiple div blocks. I want the container to have a fixed height of 250px, and be scrollable for any content exceeding this height. Here is the code snippet: http://jsfiddle.net ...

Creating two submenus in the sidebar: a step-by-step guide

I am looking to implement a feature where clicking on the sidebar menu will reveal 2 submenus. Here is what I have implemented: $(document).ready(function () { $("[data-toggle]").click(function () { var toggle_el = $(this).data("toggle"); ...

Making a CSS table fit perfectly inside a container

After reading numerous recommendations on the subject, none of them seem to be effective in my particular situation. The issue lies with a table that is nested within a container ('div' element) as shown below: <div class="container"> ...

The card header in Bootstrap card grid does not have the ability to extend all the way to the edge of

Utilizing bootstrap 4 within Laravel, I create blade.php template files. Here is a snippet of my code. The card grid layout appears satisfactory, however, there seems to be some empty space between the card titles and the edges of the cards. <div id=" ...

How can I display different data values on each individual circle counter, rather than all circles showing the same data?

Hey there! I'm trying to get my circular counters to display the counter value that I specify in their class and data-percent. However, currently all four counters are only showing the data from the first counter, even though I've set different d ...

How to ensure HTML elements are styled to occupy the full width of their parent container while respecting the minimum width requirement

Is there a way to make HTML elements have a width ranging from 150px to 200px while filling up 100% of their parent's width? Check out Image 1: https://i.sstatic.net/nYNGp.jpg And here is Image 2 (after resizing the window): https://i.sstatic.net/ ...

PHP mail function does not properly align HTML table outputs

After fetching data from the database and inserting it into an HTML table, everything appears fine. However, upon pressing the send button to email the content, sometimes the alignment of the HTML table is disrupted in the email. It seems like specific col ...

The last value label in Google Charts bar chart getting cut off

I've searched extensively for a solution to this issue regarding the haxis labels, but I have not been able to find one that addresses it... In the image provided below, you'll observe that the last percentage label on the horizontal axis is mis ...

Refresh your textarea content using the replace method in jQuery

My goal is to extract and manipulate specific values within a user-entered code using jQuery. The code includes custom tags called setting, which I want to extract and display in input fields for easy editing. I have successfully retrieved and displayed th ...