在页面中间居中动态分区的最佳途径 [英] Best Way to Centre Dynamic Div in Middle of Page

查看:92
本文介绍了在页面中间居中动态分区的最佳途径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这类事情已经有很多问题,但我希望能够在页面中间居中放置一个div,并且无论页面的宽度或高度如何都始终保持在页面中间。



我猜测最好是使用一些javascript来计算元素的宽度,然后再减去一半。 / p>

要清楚这些事情:

  .myDivHere {
position:absolute;
剩下:50%;
top:50%;
text-align:center;
width:20%;
身高:20%;
margin-left:-273px; / *由js脚本设置的半宽* /
margin-top:-132px; / *由js脚本设置的半高* /
}

我已经设置了宽度和高度为20%,因为我希望这个div能够保持其相对于浏览器窗口的大小(对于移动支持等)。任何想法?

解决方案

除非我遗漏了某些东西,否则您可以放弃JavaScript并使用纯CSS:

  div {
position:absolute;
背景:红色;
width:20%;
身高:20%;
top:0;
bottom:0;
剩下:0;
right:0;
margin:auto;
}

jsFiddle示例


I know this sort of thing has been asked a lot but I want to be able to centre a div in the middle of the page and have it always stay in the middle of the page no matter how wide or tall it gets.

I'm guessing that it would be best to use some javascript to work out how wide the element will be and then half that amount to take away from the margin.

To clear things up, this sort of thing:

.myDivHere {
    position: absolute;
    left: 50%;
    top: 50%;
    text-align: center;        
    width: 20%;
    height: 20%;
    margin-left: -273px; /*half width set by js script*/
    margin-top: -132px; /*half height set by js script*/
}

I have set the width and height to be 20% as I want this div to be able to retain its size relative to the browser window (for mobile support and such). Any ideas?

解决方案

Unless I'm missing something you can forgo the JavaScript and use plain CSS:

div {
    position:absolute;
    background:red;
    width:20%;
    height:20%;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
}

jsFiddle example

这篇关于在页面中间居中动态分区的最佳途径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆