跨浏览器中心

时间:2013-01-31 15:23:53

标签: html css

我有一个元素,它是div id中的图像。我打算将这个页面打造成一个正在构建的页面。我使用“margin:auto”css命令创建了div。什么是垂直的,我可以将div自动中心放到网站访问的任何浏览器上?

新手这个不知道如何做整个JSFiddle的事情lol

也是一个网址:http://nerissagrigsby.com/?page_id=5

我的CSS:

#openpagesig {
width: 803px;
height: 283px;
margin: auto;
}

我的HTML:

<body>
<div id="openpagesig">
    <img src="img/LoginSignature.png" width="803" height="283" alt="Login Signature"
    />
</div>
<!-- Open Page Signature -->
</body>

4 个答案:

答案 0 :(得分:3)

您是否尝试过以下CSS:

.inTheMiddle { /* or "#myImageId" (or just "img" if it's the only one) */
    position: absolute; /* or "fixed" */

    /* The element you want to place in the middle of the page
       center should have explicitly defined dimensions: */
    width: 100px;
    height: 100px;

    top: 50%;
    margin-top: -50px; /* offset back at exactly half height of the element */
    left: 50%;
    margin-left: -50px; /* offset back at exactly half width of the element */
}

这是a working example

我是否需要提及,即使在Internet Explorer 5.5中也能正常工作! ...但我怀疑这个浏览器仍然与任何人相关。

请参阅下图,了解负边距如何帮助:

How negative margins work to offset an element

答案 1 :(得分:0)

尝试类似:

.centeredDiv {
    width:17em;
    height:9em;
    position:absolute;
    left:50%;
    top:50%;
    margin:-135px 0 0 -155px;
    padding:1em;
    background-color:#fffff7;
    opacity:0.67;
    filter:alpha(opacity=67); /* for IE8 and earlier */
    border:2px solid #191919;
}

显然编辑测量和颜色以适应。

答案 2 :(得分:0)

我个人使用这样的东西:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  </head>
  <body>

    <div class="container">
        <div class="container-content">
            <div class="content">
              <img src="//placehold.it/803x283" />
            </div>
        </div>
    </div>
  </body>
</html>


<style>

  html, body {
    height: 100%;
  }

  .container {
    display: table;
    width: 100%;
    height: 100%;
    margin: auto;
  }

  .container-content {
    display: table-cell;
    width: 100%;
    vertical-align: middle;
  }

  .container-content > .content {
    max-width: 803px;
    width: 90%;
    margin-left: auto;
    margin-right: auto;
  }

</style>

这个解决方案效果非常好,因为它不仅垂直居中内容,而且如果浏览器窗口高度太小而无法全部显示,您仍然可以滚动查看所有内容,这是主要缺点之一使用其他方法。

示例:

http://jsbin.com/owayec/2/

答案 3 :(得分:0)

您遇到的问题与在页面上垂直对齐div元素有关。这是HTML和CSS编码中的常见问题。

一种解决方案是在外部div标记中包含容器元素。外部div应设置为display: table;position: fixed;,同时设置为100%widthheight。使用div属性将内部display: table-cell;设置为vertical-align: middle;

此外,外部div应该有text-align: center;,以便将其子元素居中。

以下是您需要的代码:

.outer { 
  display: table;
  height: 100%;
  width: 100%;
  text-align: center;
  position: fixed;
}
.container {
  display: table-cell;
  vertical-align: middle;
}

jsbin的一个例子: http://jsbin.com/otolot/1/

尝试调整窗口大小以确定其有效。