ttaaoossuu
ttaaoossuu

Reputation: 7884

Flex item not centering in IE

I'm trying to position a small box in the center of the page on both axes. I got it working in Chrome, Firefox and Edge, but IE still misaligns. The box seems stuck in the bottom right corner of what appears a virtual box scaled 200% compared to my content.

enter image description here

I tried changing flex attributes of .content and wrapping it into another <div /> but to no avail.

How can I get the box centered in IE?

html, body {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  position: absolute;
  width: 400px;
  height: 200px;
  background-color: #333333;
}
<div class="content">

Upvotes: 1

Views: 649

Answers (2)

Zhi Lv
Zhi Lv

Reputation: 21363

Try to remove the position property. Code as below:

html, body {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  width: 400px;
  height: 200px;
  background-color: #333333;
}

The result in IE browser like this:

enter image description here

Upvotes: 1

Michael Benjamin
Michael Benjamin

Reputation: 371093

The Problem

Absolutely-positioned children of a flex container are taken out of the normal flow of the document.

In fact, they are not even flex items, because they don't accept flex properties.

from the spec:

§ 4.1. Absolutely-positioned Flex Children

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

Here is why your layout works anyway in Chrome, Firefox and Edge:

continuing with the spec:

The static position of an absolutely-positioned child of a flex container is determined such that the child is positioned as if it were the sole flex item in the flex container, assuming both the child and the flex container were fixed-size boxes of their used size. For this purpose, auto margins are treated as zero.

read more >>

However, IE11 provides only partial support for the current flexbox specification, which may explain the rendering difference.

Solution

Since your content item isn't doing anything flex-related, just use a standard, non-flex method for horizontal and vertical centering.

body {
  height: 100vh;
  position: relative;
}

.content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  height: 200px;
  background-color: #333333;
}
<div class="content">

The centering method above is explained here:

Upvotes: 2

Related Questions