NaOH
NaOH

Reputation: 459

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>

Upvotes: 0

Views: 3903

Answers (3)

Achint
Achint

Reputation: 817

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/

Upvotes: 1

user1726343
user1726343

Reputation:

You can divide up the page width like so:

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

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157334

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

Upvotes: 2

Related Questions