最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to dynicamlly center the center of a div based on screen size - Stack Overflow

programmeradmin4浏览0评论

I really thought this would be simple but i'm losing my mind! I just simple want to center a div in the div of the screen. But not that top left of the div to the center of the screen but the center of the div in the center.

Here is my div css

.box
{
    padding-top:20px;
    padding-left:5px;
    background-color: #ffffff;
    background-color: rgba(221,221,221,0.5);
    border: 1px solid black;
    border-radius: 25px;
    filter: alpha(opacity=90);
    height: 125px;
    width: 250px;
    z-index: 1;
}

<form id="form1" runat="server">
<div id="box"><div>
</form>

Thanks! I couldnt figure out how to get the html to side in a code block. This is center horizontally and vertically.

I really thought this would be simple but i'm losing my mind! I just simple want to center a div in the div of the screen. But not that top left of the div to the center of the screen but the center of the div in the center.

Here is my div css

.box
{
    padding-top:20px;
    padding-left:5px;
    background-color: #ffffff;
    background-color: rgba(221,221,221,0.5);
    border: 1px solid black;
    border-radius: 25px;
    filter: alpha(opacity=90);
    height: 125px;
    width: 250px;
    z-index: 1;
}

<form id="form1" runat="server">
<div id="box"><div>
</form>

Thanks! I couldnt figure out how to get the html to side in a code block. This is center horizontally and vertically.

Share Improve this question edited Sep 24, 2013 at 15:48 asked Sep 24, 2013 at 15:38 user222427user222427 1
  • 1 margin:auto will get it centered horizontally – Andrew Hall Commented Sep 24, 2013 at 15:40
Add a ment  | 

3 Answers 3

Reset to default 4

Use position:absolute if you need it centred both horizontally and vertically:

#box {
    position:absolute; 
    top:0; left:0; right:0; bottom:0; 
    margin:auto;
    /* etc */
}

http://jsfiddle/wcFMw/

To center horizontally:

margin:auto;

To center vertically:

position: absolute;
top: 0; left: 0; bottom: 0; right: 0;

You could also use position: fixed to make the div centered even when scrolling the page.

Also note that you'll have to use # instead of . to select by id. . is the CSS selector used for class.

JsFiddle

margin:0 auto;

Add this property to your css class.

发布评论

评论列表(0)

  1. 暂无评论