簡體   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