繁体   English   中英

水平居中DIV,与顶部或底部的距离固定,在窗口中不滚动

[英]Center DIV horizontally and fixed distance from top or bottom, no scrolling in window

假设我有一个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

<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上真left50%使之水平居中

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

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

无论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/

如何强制一个<div>滚动时与屏幕顶部保持固定距离?</div><div id="text_translate"><p> 我想在顶部间距固定为 30px 的网页上放置一个带有较长文本的&lt;div&gt;元素。 问题是每当我向下滚动时, &lt;div&gt;不会留在原位,因此间距会消失。 我正在寻找纯 CSS 的解决方案。</p><p> 这份文件说明了我的问题:</p><pre> &lt;:DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;div style = "width; 10px: top; 50px: margin-top; 50px: padding-top; 50px: position; absolute."&gt; text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. text to enable scrolling. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</pre></div>

[英]How to force a <div> to stay a fixed distance from the top of the screen when scrolling?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM