【问题标题】:CSS Advanced Div Positioning. Center & MiddleCSS 高级 div 定位。中心和中间
【发布时间】:2012-05-03 20:33:44
【问题描述】:

我想定位<div>

  • 以 w.r.t 主体宽度居中
  • 到中间,w.r.t 身高

div 将具有以下属性:

  • div 的宽度将为 90%
  • div 自动的高度,最小。会知道的

【问题讨论】:

  • 你可以使用margin(left,right) 5%来模拟居中宽度的效果。
  • 垂直定位是个问题

标签: css html positioning alignment


【解决方案1】:

我已经在 IE8、Firefox、Chrome 中对此进行了测试。它在 IE7 中不起作用。

如果您需要它在

Live Demo

HTML:

<div id="container"> 
    <div id="content"> 
        <input type="button" value="click me" onclick="javascript:document.getElementById('content').innerHTML += 'i i i i i i i i i i i i i i i i i i i i i i i i i<br />';" /><br />
        i i i i i i i i i i i i i i i i i i i i i i i i i<br />
        i i i i i i i i i i i i i i i i i i i i i i i i i<br />
        i i i i i i i i i i i i i i i i i i i i i i i i i<br />
        i i i i i i i i i i i i i i i i i i i i i i i i i<br />
    </div> 
</div>

CSS:

html, body {
 margin: 0;
 padding: 0;
 border: 0;

 width: 100%;
 height: 100%
}

body {
 display: table
}

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

#content {
 background: red;
 width: 90%;
 margin: 0 auto;
 min-height: 150px
}

【讨论】:

  • 每当我在 CSS 中看到 display: table 和 consorts 时,我都会有复杂的感觉,我总是想知道:“为什么不直接使用 &lt;table&gt; 而不是所有这些乱七八糟的东西?”。 divitis 你会走多远?
【解决方案2】:

您可以将高度居中like this(注意浏览器兼容性)。

对于居中宽度:您可以使用position: absolute;left: 50%;,以及它们margin: -num;。在页边空白处,将 num 替换为 div 宽度的一半。

【讨论】:

    【解决方案3】:

    用这个设置 div。我相信它在 IE 7 及更低版本中不起作用。糟糕的IE....

    边距:自动; 上:0;右:0;左:0;下:0; 位置:绝对;

    【讨论】:

    • 适用于 .. 图像有宽度和高度。否则,必须将两个选项都添加到样式中才能使用,例如div
    【解决方案4】:

    你可以使用 margin(left,right) 5% 来模拟居中宽度的效果。

    关于高度居中,我不知道单独使用 css 可以做到的方式(因为未知的垂直尺寸)。但你可以尝试使用 javascript 来做到这一点。

    这里是一个例子:http://www.demtron.com/blog/post/2009/01/14/Centering-a-DIV-Window-with-Cross-Browser-JavaScript.aspx(你可以忽略检测窗口大小部分)。

    【讨论】:

      猜你喜欢
      • 2016-01-12
      • 1970-01-01
      • 2013-08-12
      • 2017-04-09
      • 2013-07-13
      • 2020-10-25
      • 2013-06-04
      • 1970-01-01
      • 2015-05-01
      相关资源
      最近更新 更多