Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS (position:absolute + left:50% = max-width:50%)?

Tags:

html

css

I'm working on a website where I'm having a temporary problem, I've a div with CSS like this:

.box{
    position: absolute;
    width: auto;
    max-width: 75%;
    left: 50%;
    transform: translate(-50%,0);
    -ms-transform: translate(-50%,0);
    -webkit-transform: translate(-50%,0);
    background: #000;
    color: #fff;
}

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 50%

My question is from where did the box2 get 50% width ?? And how can I fix that issue ?

Thanks in advance

like image 265
MujtabaFR Avatar asked Jul 26 '14 09:07

MujtabaFR


2 Answers

You may achieve the desired layout using an extra tag (a span for example)

DEMO

HTML :

<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>
</div>

CSS :

.box{
    position: absolute;
    width: 100%;
    text-align:center;
}

.box1{
    top: 20px;
}

.box2{
    top: 100px;
}
.box span{
    display:inline-block;
    max-width:75%;
    background: #000;
    color: #fff;
    text-align:left;
}
like image 158
web-tiki Avatar answered Sep 28 '22 06:09

web-tiki


Use style width: fit-content;. Example:

.center-wrapper {
  position: absolute;
  left: 50%;
  top: 0;
  width: fit-content;
  transform: translate(-50%);
  background-color: yellow;
}

This "center-wrapper" (your "box") now grows with child and also is centred.

like image 33
Dominik Avatar answered Sep 28 '22 08:09

Dominik