skip to Main Content

I have a bunch of flex-items in a container. The flex-direction is set to column. One of the elements has a little bit more text, so that its contents wraps into a new line. Now the element’s width automatically becomes 100% of the width of the parent. How can I prevent this from happening?

To make it a bit clearer: The "green" should "stop" after the second "Twentyone".

.parent {
  border: 1px solid black;
  display: flex;
  flex-direction: column;
  width: 200px;
  align-items: flex-start;
}

.child:nth-child(odd) {
  background-color: chartreuse;
}

.child:nth-child(even) {
  background-color: chocolate;
}

.long {
  /* ??? */
}
<div class="parent">
  <div class="child">One</div>
  <div class="child">Two</div>
  <div class="child long">Twentyone Twentyone Twentyone</div>
  <div class="child">Four</div>
  <div class="child">Five</div>
</div>

enter image description here

2

Answers


  1. simply you can use width to solve this problem

            .long {
                width: min-content;
            }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            .parent {
                border: 1px solid black;
                display: flex;
                flex-direction: column;
                width: 200px;
                align-items: flex-start;
            }
    
            .child:nth-child(odd) {
                background-color: chartreuse;
            }
    
            .child:nth-child(even) {
                background-color: chocolate;
            }
    
            .long {
                width: min-content;
            }
        </style>
    </head>
    
    <body>
        <div class="parent">
            <div class="child">One</div>
            <div class="child">Two</div>
            <div class="child long">Twentyone Twentyone Twentyone</div>
            <div class="child">Four</div>
            <div class="child">Five</div>
        </div>
    </body>
    
    </html>
    Login or Signup to reply.
  2. You can use the <span> element.

    .parent {
      border: 1px solid black;
      display: flex;
      flex-direction: column;
      width: 200px;
      align-items: flex-start;
    }
    
    .child:nth-child(odd)>span {
      background-color: chartreuse;
    }
    
    .child:nth-child(even)>span {
      background-color: chocolate;
    }
    <div class="parent">
      <div class="child"><span>One</span></div>
      <div class="child"><span>Two</span></div>
      <div class="child long"><span>Twentyone Twentyone Twentyone</span></div>
      <div class="child"><span>Four</span></div>
      <div class="child"><span>Five</span></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search