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.caixa
isbreakingthelineontherightmarginoftheparent.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>