开发者

vertical align - z-index

I am trying to align 开发者_StackOverflowvertically a modal box. But the margin-top:50% did not work as i expect. Basically i want a square centered on another square.

<style type="text/css">
#modal {
    width: 300px;
    height: 300px;
    z-index: 100;
    background-color: red;
    margin: 0 auto;
    position:relative;
    margin-top:50%; //problem here

}

#content {
    position: absolute;
    width:950px;
    height: 950px;
    margin: 0 auto;
    background-color: green;
}

#replace {
 width:950px;
 height:500px;   
}


</style>

<div id="replace">
<div id = "content"></div>
<div id="modal"></div>
</div>

thanks

demo


Instead of margin you need to use top:325px; for #modal


If it's not too much trouble to have the modal inside the content div, you might want to try this HTML:

<div id = "content">
    <div id="modal"></div>
</div>

...with this CSS:

#modal {
    width: 300px;
    height: 300px;
    background-color: red;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -150px;
    margin-top: -150px;
}

#content {
    position: absolute;
    width: 550px;
    height: 550px;
    background-color: green;
}

Demo

Basically you're absolutely-positioning the modal div inside the content div, and telling it to go start at 50% from the top and 50% from the left. This will center the top-left corner of the modal, but not the div as a whole. To center the div as a whole, you then have to add a negative margin to move it back up and to the left. The amount of the negative margin is half the height/width of the modal div.

If you want to keep the same HTML, you can still accomplish the same thing using this technique, just make sure to do position: relative on your replace div so that any absolutely-position children are positioned relative to it.


Add position: relative; to your container if you want absolutely positioned elements inside it to be positioned relative to it:

#replace {
  position: relative;
  width: 950px;
  height: 500px;
}

Then set to top value of the item you want to position. One thing to note here, your #replace div is the container here, but it's smaller than the #content div, so when you position #modal, you're going to have to give it specific pixel values to get it centered over #content.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜