简体   繁体   中英

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

Say I have a div that I want to be centered horizontally, and set at a fixed distance from the top or bottom of the window. I want to set its width to say 75%, and its height to be fluid depending on dynamic content. The page will never have content extending past the viewport so it won't ever scroll. How can I do this with CSS? HTML is here, basically:

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

You can do it like this Demo

HTML

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

CSS

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

Explanation: give position: absolute; to your div and the real trick to get it centered horizontally is give margin-left which will be half of your total width of the div and give left as 50% to bring it horizontally centered

You can divide up the page width like so:

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

Are you keeping the distance from the top or bottom fixed, irrespective of the amount of content in the div?

If so, you can try something like this:

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

and the css classes:

#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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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