Chris W. Chris W. - 7 months ago 16
HTML Question

Centering Div in IE9 without fixed Height/Width

Can I borrow someone's eyes before I drop kick this damn thing out the window?

SHORT VERSION: What's the right way to x,y center a div reliably in IE9 when it can not be fixed height/width?

Scenario: I'm customizing the templates of ping federate server that we pass through a windows store app for auth. I mention this because windows store apps (Not to be confused with UWP) uses a jank version of IE9.

My problem...which I can't even go make a damn codepen for since they don't support IE9 anyway....is I'm just trying to center the first child

div
both vertically and horizontally.

Now then, IE9 doesn't support flexbox, so no love there. I am however able to do;

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);


which does indeed center it nicely, looks great on everything EXCEPT IE as it displays a large white space at the bottom of the screen. Which in turn, also causes scrollbars to appear which aren't even necessary...

Since the
div
can not be of a fixed width/height I have not gotten other fixes to work. It also doesn't help I've been doing .NET stuff so long my css is rusty.

So can someone start my weekend off right and enlighten me to some IE Kung Fu fix so I may praise your name and toast beer to you this evening? :)

Hopefully the snippet below (ran in IE as IE9) will help visualize my issue with this stupid whitespace at the bottom that has become my nemesis...



html, body {
height: 100%;
width: 100%;
}

body {
background-image: url("https://static.pexels.com/photos/1350/blur-blurred-background.jpg");
background-size: cover;
background-repeat: no-repeat;
background-position: fixed;
}

div {
min-width: 250px;
min-height: 250px;
background: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}

<div></div>




Answer

the old way was with an extra element, but a pseudo will do for IE9 :

html, body, body:before {
  height:100%;
  text-align:center;
  }
body:before {
  content:'';
  display:inline-block;
  margin-left:-0.25em;
  width:0;
  vertical-align:middle;
  }
div {
    min-width: 250px;
  max-width:99.5%; /* or  white-space on body for security to avoid div wrap under pseudo, 
  do not forget to reset to normal if you choose so */
  min-height: 250px;
  background: green;
  display:inline-block;/* i'll be against top or left without dissepearing  if window is too small */
  width:  ;
  height:  ;
  vertical-align:middle;
  /* text-align:left; */
  }

/* not IE 9 , bg-cover ? */
body {
  background-image: url("https://static.pexels.com/photos/1350/blur-blurred-background.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: fixed;
}
<div></div>