I'm working on a website where I'm having a temporary problem, I've a
div with CSS like this:
You can see a simple JSFiddle here, where the
box1 is working correctly, it has short text and the
width: auto; is working perfectly ...
But the second box
box2 has long text and
max-width: 75%;, but it's not working correctly, you can notice that its width looks like
My question is from where did the
50% width ?? And how can I fix that issue ?
Thanks in advance
You may achieve the desired layout using an extra tag (a
span for example)
<div class="box box1"><span>box1 Lara had been back and</span></div>
<div class="box box2">
<span>box2 Lara had been back and forth along the river path many times in her short life. Her people had not created the path, it had always been there, like the river, but their deerskin-shod feet and the wooden wheels of their handcarts kept the path well worn. Lara’s people were salt traders, and their livelihood took them on a continual journey</span>
First you have
left: 50%;. This makes the div 50% width since it has
width: auto; and there are only 50% of the page left for it to fill. After that, the div is moved 50% of it's own width to the left, to be centered.
So we can conclude that the
width: auto; and
left: 50%; is calculated before
transform: translate(-50%,0);. Probably in that order.
So that's the answer to you're question why the div doesn't grow bigger than 50%.
Discussion courtesy of: Niklas
Are you just trying to center your divs? Can you set the horizontal margin to
margin: 10px auto;
In your original code, the width of your divs gets limited to 50% of the window due to the absolute positioning of them 50% from the left side of the window.
The transform then slides the divs back over to the left by 50% of the window width, but they keep their reduced size.
The automatic width allowed the upper div's width to collapse downward to its contained text. This wasn't relevant to the lower div, since the length of its text would exceed the width of the window if allowed.
I guess this can solve your issue without changing your structure.
If the element has 'position: absolute', the containing block is
established by the nearest ancestor with a 'position' of 'absolute',
'relative' or 'fixed' .
Where the html tag element is the containing block in your case, a possible solution would be to add a container
<div> and set its position to
relative , demo.
You type max-width: 75% this mean your div could have width less than 75% so
If something inside div is bigger then 75% div will still have 75% but
if something inside div is lower then 75% div will suit width to this element.
Try to add width:75% instead
This recipe can be found in it's original form on Stack Over Flow.