0

I am new to CSS. I want to keep the div always at the center of the screen. I know by positioning we can achieve it but that is only when we have fixed width and height. What my requirement is, I want to have a div with fixed width but no fixed height. I want it to get adjusted to the center based on the content inside it using CSS.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Hi would appreciate it if you could give us a jsFiddle to play around with. – w3shivers Dec 04 '14 at 07:54
  • And yes, it _is_ a repeated question: http://stackoverflow.com/questions/59309/how-to-vertically-center-content-with-variable-height-within-a-div – Salman A Dec 04 '14 at 07:57

2 Answers2

0

You are looking for transform: translateY(-50%) property. Here is an example:

.main {
    width: 200px;
    position: fixed;
    background-color: red;
    position: fixed;
    top: 50%;
    left: 0px;
    right: 0px;
    transform: translateY(-50%);
    margin: auto;
}

Working Fiddle

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
0

Just do something like this and you can be sure that it will always be in the middle.

HTML

<div id="outer">
<div id="content"></div>
</div>

CSS

* {
    margin: 0 auto; /* centers everything except if otherwise floated 
   or affected by positioning positioning and margin property values */
}


#outer {
    width: 200px;
    height: auto;

}


#content {
    width: 200px;
    height: 100%;
    position: absolute;
    background-color: green;
    bottom: 0;

}

See working example here

Solution: Wrapped the DIV in question in a none floated div that listen to the first block of CSS code and I didn't do anything that will affect its position.

Sleek Geek
  • 4,638
  • 3
  • 27
  • 42