Gauthier Tassin
Gauthier Tassin

Reputation: 606

How to set sibling element's width to flex item which contains long word

I'm trying to do this :

enter image description here

The flex-item img must define the flex-container width and the other flex-item (the div with "a" and "aaaaaaa...") must into the flex-container but must not make the flex-container grow.

Also, i don't want to fix a width of text flex-item in px because the image width is dynamic. How can i do that without using javascript ?

I made this code snippet according to my image to help :

.flex-container {
  display: flex;
  flex-direction: column;
  border: 3px blue solid;
}

.random-image {
  width: 50px;
  height: 50px;
  border: 3px red solid;
}

.first-text, .second-text {
  border: 3px orange solid;
}

.second-text {
  word-break: break-all;
}
<div class="flex-container">
  
  <div class="random-image"></div>
  
  <div class="first-text">a</div>
  
  <div class="second-text">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>
  
</div>

Upvotes: 1

Views: 950

Answers (1)

Kameron
Kameron

Reputation: 10846

Remove the fixed width on the image div and use width: min-content; on the flex-container as well as the random-image div. This should work nicely for you.

.flex-container {
  display: flex;
  flex-direction: column;
  border: 3px blue solid;
  width: min-content;
  height: fit-content;
  padding: 10px;
}

.random-image {
  border: 3px red solid;
  width: fit-content;
}

.first-text, .second-text {
  border: 3px orange solid;
}

.second-text {
  word-break: break-all;
}

.first-text {
  width: fit-content;
  margin: 1em auto 1em auto;
}
<div class="flex-container">
  
  <div class="random-image"><img src="https://dummyimage.com/600x400/000/fff"></div>
  
  <div class="first-text">a</div>
  
  <div class="second-text">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>
  
</div>

Upvotes: 1

Related Questions