friedman
friedman

Reputation: 685

Translate(-50%, -50%) and position: relative issue on different browsers

I've an issue trying to translate the element by -50%, -50%.

I've code as below but it executes differently in Firefox and in Chrome. Firefox renders what I am trying to achieve (the center position of element with class .two) but Chrome just loses it.

What I've figured out so far is that it's probably the case of position: relative but I need it instead of absolute to calculate the width and height of the element in relation to parent.

body, html {
  height: 100%; width: 100%;
  margin: 0; padding: 0;
}

.one {
  background: red;
  width: 100%;
  height: 100%; /* for anothet purposes */
  min-height: 30%;
  max-height: 50%;
}

.two {
  background: orange;
  display: inline-block;
  height: 80%;
  width: auto; max-width: 90%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
<div class="one">
<div class="two">ABC</div>
</div>

Upvotes: 1

Views: 520

Answers (1)

Danield
Danield

Reputation: 125601

The issue here is that the container element has no explicitly-set height. True, it has min-height and max-height set, but not the height property. (even though the calculated height is the value of the min-height)

Now top: 50% means: 'move the element down by 50% of the container's height ' so:

In Chrome: top: 50% moves the inner element down 50% x 0px (the container's set height) = 0px and then transform moves it up by half of it's own height.

Firefox however interprets top: 50% as 50% of the calculated height of the container.

If you set an explicit height on the container this will work in Chrome as well:

body, html {
  height: 100%; width: 100%;
  margin: 0; padding: 0;
}

.one {
  background: red;
  width: 100%;
  height: 150px; /* for anothet purposes */
  min-height: 30%;
  max-height: 50%;
}

.two {
  background: orange;
  display: inline-block;
  height: 80%;
  width: 80%;
  max-width: 90%;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
<div class="one">
<div class="two">ABC</div>
</div>

Upvotes: 2

Related Questions