Center absolute positional div with unfixed width

I do not know and cannot know the width of the absolute div, I need to focus. It must be absolutely positioned because it overlaps other elements (z-index trick). This is my main structure.

<div style='position:relative'> <div></div> <div style='position:absolute'>...</div> </div> 

The first child div is not completely positioned to give the parent value its height and width. The second div should overlap its siblings and center horizontally.

The above structure is just an illustration of my dilemma, in reality the parent div will have many children, not all of them will be divs, none of their dimensions will be known.

Thanks, I'm going to sleep now ...

+4
source share
3 answers

Well, I don’t think it’s possible to do this using only CSS, because to center an absolute div you always need to have a width to use β†’ "left: 50%; margin-left: [width / 2] points ;."

In any case, you can use some javascript / jQuery code to get the width of your div and then dinamicaly set the CSS width property.

Read the following: http://api.jquery.com/width/ http://api.jquery.com/css/#css2

+2
source

A way to do this would include a small amount of js, but not so much. Although first I will go through css:

First, you need to add:

 left: 50%; 

This gives the end of the div to the left halfway through the page. Then give it a class so that we can reference it in javascript, for example:

 <div style='position:relative'> <div class='center-absolute'>Content</div> </div> 

So we can reference it in css and js. We use a class because you should only use an identifier for a single element.

Here is the css you will need for .center-absolute :

 .center-absolute { position: absolute; left: 50%; } 

Then for js. Since there may be several elements, we need a for loop to iterate between them:

 var $centerAbsolute = document.getElementsByClassName('center-absolute'); for (i = 0; i < $centerAbsolute.length; i++) { $centerAbsolute[i].style.marginLeft = $centerAbsolute[i].offsetWidth / 2 * -1 + 'px'; } 

This repeats through all elements with the center-absolute class and gives them a field to the left of minus half the width of the element that centers it.

Here is a demonstration of the working script:

http://jsfiddle.net/Hive7/FqJ7T/

0
source

Although this is deprecated, <div align="center"> should work.

-1
source

Source: https://habr.com/ru/post/1314402/


All Articles