0

I have a div whose size depends on its content. I want to have an absolute child which takes the whole space.

In Firefox I get the wanted result but not in Chromium. How to fix it?

Which browser is rendering against the specification?

<div style="position:relative;float:left;">
    <div style="position:absolute;display:table;left:0;top:0;height:100%;width:100%;background:red;">
        <div style="display:table-cell;vertical-align:middle;">TEST</div>
    </div>

    <!-- this is an img in real with unknown size -->
    <div style="width:200px;height:200px;background:yellow"></div>
</div>
somega
  • 739
  • 3
  • 13
  • 1
    display:table is the culprit, remove it and use another way to center your element (https://stackoverflow.com/a/22218694/8620333) – Temani Afif Jul 27 '19 at 15:13
  • But why remove it? It should be valid. – somega Jul 27 '19 at 15:19
  • 1
    you are using is to center your element and it's not the best way to do it, it's more a hacky way and as you noticed it doesn't work properly in all the browsers. – Temani Afif Jul 27 '19 at 15:23

1 Answers1

0

You just need to change the display of this div to display:flex and use margin: auto to center the text:

<div style="position:relative;float:left">
    <div style="position:absolute;display:flex;left:0;top:0;height:100%;width:100%;background:red;">
        <div style="margin: auto">TEST</div>
    </div>

    <!-- this is an img in real with unknown size -->
    <div style="width:200px;height:200px;background:yellow"></div>
</div>

Or with display: flex and align-items: center:

<div style="position:relative;float:left">
    <div style="position:absolute;display:flex;left:0;top:0;height:100%;width:100%;background:red;align-items: center">
        <div>TEST</div>
    </div>

    <!-- this is an img in real with unknown size -->
    <div style="width:200px;height:200px;background:yellow"></div>
</div>
Cuong Le Ngoc
  • 8,001
  • 2
  • 8
  • 33