【问题标题】:Center DIV horizontally and fixed distance from top or bottom, no scrolling in window水平居中 DIV 并与顶部或底部固定距离,在窗口中不滚动
【发布时间】:2012-10-30 14:10:58
【问题描述】:

假设我有一个要水平居中的 div,并设置在距窗口顶部或底部的固定距离处。我想将其宽度设置为 75%,并将其高度设置为根据动态内容而变化。页面永远不会有超出视口的内容,因此它永远不会滚动。我怎样才能用 CSS 做到这一点? HTML 在这里,基本上:

<body>
  <div id="main">
    <div id="div_in_question">
      Omg stuff goes here it will probably change though via jQuery.
    </div>
  </div>
</body>

【问题讨论】:

  • 你为什么要绝对定位这个?您应该相对定位它,它会根据您的需要表现得更好。

标签: html css css-position


【解决方案1】:

你可以这样做Demo

HTML

<div class="container"></div>

CSS

.container {
    height: 300px;
    width: 75%;
    position: absolute;
    background-color: #ff0000;
    margin-left: -37%;
    left: 50%;
}

说明:将position: absolute; 赋予div,使其水平居中的真正技巧是赋予margin-left,这将是div 总宽度的一半,并将left 赋予50%使其水平居中

【讨论】:

  • 这是页面:new.e17.paca.arvixe.com 出于某种原因,我无法让它工作。它很接近,但是您可以查看是否稍微调整了窗口大小,使其不完全居中,但看起来更靠近窗口的右侧(至少在 Chrome 中)。知道为什么会这样吗?
  • @NaOH 这是因为你使用所有绝对定位的div
  • 哦?这有什么关系?
【解决方案2】:

你可以像这样划分页面宽度:

margin-left:14.5%;
margin-right14.5%;
width:75%;

【讨论】:

    【解决方案3】:

    无论 div 中的内容量如何,您是否保持与顶部或底部的距离固定?

    如果是这样,您可以尝试以下方法:

    <div id='outer'>
         <div id='inner'>                    
             SOme text hereSOme text hereSOme text hereSOme text hereSOme text hereSOme  
         </div>
    </div>
    

    还有 css 类:

    #outer{
    height:150px;
    background-color:red
    }
    
    #inner{
    width:75%;
    height:auto;
    background-color:yellow;
    max-height:100%;
    overflow:hidden;
    margin-left:14.5%;
    margin-right:14.5%
    }​
    

    http://jsfiddle.net/hbRHW/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      相关资源
      最近更新 更多