noclist noclist - 10 days ago 5
CSS Question

HTML/CSS - auto size the width of content in a wrapper

I have a content div with a variable length of content, horizontally.
I would like the width of this content div to auto-size depending on the length of it's content. For example, I would like to be able to remove the arbitrary "20%" value, and have the div size accordingly. Currently removing the 20% value from the width is forcing it to resize to 100% of it's container. What CSS am I missing?

Fiddle



.wrapper {
border: 2px solid green;
}
.content {
margin: 0 auto;
text-align: center;
border: 2px solid orange;
width: 20%;
}

<div class="wrapper">
<div class="content">
<span>One</span>
<span>Two</span>
<span>Three</span>
<span>Four</span>
</div>
</div>




Answer

Put text-align:center on the wrapper and set the display of the content div to inline or inline-block:

.wrapper {
  border: 2px solid green;
  text-align:center;
}
.content {
  margin: 0 auto;
  text-align: center;
  border: 2px solid orange;
  display: inline;
}
<div class="wrapper">
  <div class="content">
    <span>One</span>
    <span>Two</span>
    <span>Three</span>
    <span>Four</span>
  </div>
</div>