2

I have a centered div (using absolute positioning and transform:translate(-50%,-50%) as described here). When the content of the child div is short everything works fine. When the content is long, then the child div width is limited to 50% of the container div (probably because left is set to 50%).

Is there a way to allow the child div to expand to the full width only when the content is long?

.container {
  position: relative;
  display: inline-block;
  width: 200px;
  height: 200px;
  margin-left: auto; 
  margin-right: auto;
  border: 2px solid black;
}

.child {
  position: absolute;
  transform: translate(-50%, -50%);
  left:50%;
  top:50%;
  background:lightgreen;
}
<div class="container">
  <div class="child">short</div>
</div>

<div class="container">
  <div class="child">long long long long long long long</div>
</div>

Edit: I found an explanation that helped me wrap my head around this in this answer.

Elad
  • 510
  • 7
  • 22

2 Answers2

1

Just add an display: table to the child div, this should give you the desired result.

.container {
  position: relative;
  display: inline-block;
  width: 200px;
  height: 200px;
  margin-left: auto; 
  margin-right: auto;
  border: 2px solid black;
}

.child {
  display: table;
  position: relative;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  background:lightgreen;
}
<div class="container">
  <div class="child">short</div>
</div>

<div class="container">
  <div class="child">long long long long long long long</div>
</div>

If you could use flexbox you can also do this:

.container {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  vertical-align: top;

  width: 200px;
  height: 200px;
  border: 2px solid black;
}

.child {
  background:lightgreen;
}
<div class="container">
  <div class="child">short</div>
</div>
<div class="container">
  <div class="child">long long long long long long long</div>
</div>
cyr_x
  • 12,554
  • 2
  • 26
  • 42
  • Changed position to relative to work in firefox, but don't know if that's what you want. – cyr_x Sep 07 '17 at 08:52
0

Add in an additional nested element to allow yourself more control over dynamic positioning and scaling of the elements in question.

.container {
  position: relative;
  display: inline-block;
  width: 200px;
  height: 200px;
  margin-left: auto; 
  margin-right: auto;
  border: 2px solid black;
  box-sizing: border-box;
}

.child {
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    text-align: center;
}

.child-inner {
    background: lightgreen;
    left: 0;
    right: 0;
    display: inline-block;
}
<div class="container">
  <div class="child"><div class="child-inner">short</div></div>
</div>

<div class="container">
  <div class="child"><div class="child-inner">long long long long long long long</div></div>
</div>
UncaughtTypeError
  • 6,718
  • 2
  • 17
  • 35