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

I am working on a site where I have a temporary problem, I have divwith CSS as follows:

.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;
}

Here you can see a simple JSFiddle where it box1works correctly, it has short text and width: auto;works fine ...

But the second block box2has long text and max-width: 75%;, but it does not work correctly, you may notice that its width looks like50%

My question is: where did the box2width come from 50%? And how can I fix this problem?

Thanks in advance

+4
source share
7 answers

(, span)

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;
}
+3

"position: absolute", "" "", "" "".

html- , <div> relative, .

+1

left: 50%;. div 50%, width: auto;, 50% . div 50% , .

, , width: auto; left: 50%; transform: translate(-50%,0);. , .

, , div 50%.

+1

max-width: 75% , div 75%,

- div , 75% div 75%, - div , 75% div .

: 75%

0

div? auto ?

.box {
  background: #000;
  color: #fff;
  margin: 10px auto;
  max-width: 75%;
}

DEMO: http://jsbin.com/riqafo/2/edit

50% - 50% .

50% , .

The automatic width allowed the top width of the div to collapse down to the text it contains. This does not apply to the bottom div, as the length of its text will exceed the width of the window, if allowed.

0
source

I suggest that this can solve your problem without changing your structure.

jsfiddle

.box{
    position: absolute;
    width: auto;
    display: table;
    max-width: 75%;
    left: 0;
    right: 0;
    background: #000;
    color: #fff;
    margin: auto;
}

.box1{
    top: 20px;
}

.box2{
    top: 100px;
}
0
source

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 a child, and is also centered.

0
source