Depend on content to determine the width, not the parent

Issue

I have the following elements:

.nav {
  width: 100%;
  background: red;
  display: flex;
}

.parent {
  background: blue;
  flex-grow: 1
}

.child {
  background: yellow;
}
<div class="nav.">
  <div class="parent">
    <div class="child">
      Logo
    </div>
  </div>
</div>

I want the Logo to be colored in Yellow, but I also want to see the color of the parent, blue color.

which basically means, I don’t want the .child to take up the width of its parent, I want it to have its own width depending on its content.

depending on its content means that I don’t want to give it static width such as 100px or 200px, I want instead it to have a dynamic width.

How to achieve that in CSS?

Solution

You can make your child inline-block, then it will only be as big as the content (plus any padding)

.nav {
  width: 100%;
  background: red;
  display: flex;
}

.parent {
  background: blue;
  flex-grow: 1
}

.child {
   display:inline-block;
  background: yellow;
}
<div class="nav.">
  <div class="parent">
    <div class="child">
      Logo
    </div>
  </div>
</div>

Answered By – Pete

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published