One option to resolve this is alignment with flex
, so 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 the explanation of your problem.
What happens is when you wear transform:translate
you this adjusts the child element on its axis and not on the parent’s axis! Keeping this in mind realize that when you play the .caixa
(which is wider than 50% of the father’s width), 50% left he breaks the line!
To better understand see in this Gif that when moving the .caixa
in the left
it breaks or not, already moving the axle X
of transform:translate
nothing happens, because these measures refer to the axis itself!
In fact the .caixa
is breaking the line on the right bank of the parent. After that you shift the element "virtually" on the axis itself, but the line remains broken by hitting the side of the parent.
TIP: If your text is just a line you can put in white-space: nowrap;
But it only works if the text has only one line!
See how it looks:
.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>
I don’t get it, you want the black square to be this big, but don’t break the line?
– Leandro Angelo
No, the html broke the line if I ask, even fitting the whole text in a single line. This break was automatic. And I didn’t want this break (only if I have to) @Leandroangelo
– caiocafardo