开发者

Center an absolute positioned div with an unfixed width

I don't know and can't possibly know the width of the absolute div I need centered. It must to be absolutely positioned because it is overlapping other elements (z-index trickery). This is my basic structure

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

The first child div is not absolutely positioned so a开发者_开发百科s to lend its height and width to the parent. The second div must overlap its siblings and be centered 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.

Thank you, I'm going to sleep now...


Well, I don't think that is posible to do that using only CSS because to center an absolute div you always need to have the width set in order to use -> "left: 50%; margin-left: [width/2]px;".

Anyway, you can use some javascript/jQuery code do get the width of your div and then dinamicaly set the CSS width property.

Please read the folowing: http://api.jquery.com/width/ http://api.jquery.com/css/#css2


The way to do this will include a small amount of js though not much. Though firstly I will go through the css:

Firstly you need to add:

left: 50%;

This gets the end of the div on the left to half way across the page. Then give it a class so that we can refer to it in the javascript for example:

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

This way we can refer to it in the css and js. We use a class as you are only supposed to use an id for one element.

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

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

Then for the js. As there may be multiple elements we need a for loop to iterate between each one:

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

This iterates through all of the elements with a class of center-absolute and gives them a margin left of minus half of the width of the element which centers it.

Here is a working fiddle demo:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜