Position absolute does not occupy 100% of the parent

1

Because a div with absolute position does not occupy 100% of the width of the parent if it fits, why does the line break before? See the example below:

.segura{
  width: 200px;
  height: 200px;
  display: block;
  position: relative;
  background-color: #eeeeee;
}
.caixa{
  width: auto;
  height: auto;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #000000;
  color: #ffffff;
}
<div class="segura">
   <div class="caixa">
       dfdf fsdfsd dsf d
   </div>
</div>

The right thing was for the black box to go without this line break, what do you do to break the line only if it reaches the width limit?

    
asked by anonymous 19.10.2018 / 17:06

1 answer

3

One option to solve this is the alignment with flex , so that you align the child element with margin:auto and not with top left , below I will explain the problem in more detail.

.segura{
  width: 200px;
  height: 200px;
  position: relative;
  background-color: #eeeeee;
  display: flex;
}
.caixa{
  margin: auto;
  width: auto;
  height: auto;
  background-color: #000000;
  color: #ffffff;
}
 <div class="segura">
   <div class="caixa">
       dfdf fsdfsd dsf d
   </div>
</div>

Now explain your problem.

What happens is that when you use transform:translate you set the child element on the axis itself and not on the parent axis! With that in mind, notice that when you play .caixa (which is wider than 50% of the parent width), 50% to the left it breaks the line!

To understand better, see in this Gif that when moving .caixa in left it will be breaking or not, already moving the axis X of transform:translate nothing happens, because these measures are referring to the axis itself!

Actually.caixaisbreakingthelineontherightmarginoftheparent.Afterthat,youmovetheelement" virtually " on the axis itself, but the line is still broken by reaching the side of the parent.

TIP:Ifyourtextisjustalineyoucanputitinwhite-space:nowrap;Butonlyifthetexthasonlyoneline!

Here'show:

.segura{
  width: 200px;
  height: 200px;
  display: block;
  position: relative;
  background-color: #eeeeee;
}
.caixa{
  width: auto;
  height: auto;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #000000;
  color: #ffffff;
  white-space: nowrap;
}
<div class="segura">
   <div class="caixa">
       dfdf fsdfsd dsf d
   </div>
</div>
    
19.10.2018 / 17:37