Anelook
Anelook

Reputation: 1277

Making div element wide enough for a text string

Is it possible to make the width of the absolutely positioned div big enough to contain the text, but not bigger? I tried inline-block, but it doesn't seem to work, because once I set the position:absolute the div will take the max width of the parent element.

Could you suggest what changes I can make to the child element, so that it float in the center of the parent div and has smallest width possible but fits the text string inside.

Here is the jsfiddle: http://jsfiddle.net/hmmrfmk0/

<div class='grand-parent'>
<div class='parent'>
    <div class='child'>
        long long long string
    </div>
</div>

.grand-parent {
    position: absolute;
    width:500px;
    height:100px;
    background-color:red;
}
.parent {
    position:relative;

    margin: 0;
    padding: 0;

    width:500px;
    height:100px;


}

.child {
    position:absolute;
    margin:auto;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background-color: #ccccc0;
    border: 1px solid black;
    height:15px;
    display:inline-block;

}

Thx!

Upvotes: 1

Views: 547

Answers (3)

Paulie_D
Paulie_D

Reputation: 115373

Yes it is. Use white-space:nowrap and remove top, left, right, bottom 0 values and the position the element where you want it. In this case, dead center of the parent div.

.grand-parent {
  width: 500px;
  height: 100px;
  background-color: red;
  margin-bottom: 10px;
}
.parent {
  position: relative;
  margin: 0;
  padding: 0;
  width: 500px;
  height: 100px;
}
.child {
  position: absolute;
  margin: auto;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #ccccc0;
  border: 1px solid black;
  height: 15px;
  white-space: nowrap;
}
<div class='grand-parent'>
  <div class='parent'>
    <div class='child'>
      long long long string
    </div>
  </div>
</div>

<div class='grand-parent'>
  <div class='parent'>
    <div class='child'>
      long long long string ong long long string
    </div>
  </div>
</div>

Upvotes: 2

Jackson
Jackson

Reputation: 3518

Try this fiddle. If you display the parent as table-cell and put vertical-align as middle then you can position vertically.

.grand-parent {
   position: absolute;
   width:500px;
   height:100px;
   background-color:red;
}
.parent {
   position:relative;

   margin: 0;
   padding: 0;

   width:500px;
   height:100px;
   text-align: center;
   display: table-cell;
   vertical-align: middle;

}

.child {
   background-color: #ccccc0;
   border: 1px solid black;
   height:15px;
   display:inline-block;
   vertical-align: middle;


}

Upvotes: 0

Simon Mason
Simon Mason

Reputation: 561

Your .child class includes left:0 and right:0

This will force the div to be as wide as it's parent, inline-block will not over-ride this.

Remove right:0 from .child and it should work as you want

Upvotes: 0

Related Questions