Antoine
Antoine

Reputation: 130

CSS div dynamic width with two values

I'd like my div to be 175px width if the text inside is shorter than this value or to take 100% of cointainer width if the text is bigger than 175px. How can I achieve this?

So far I tried to play with width, min-width and max-width but can figure it out.

.text-div {
  min-width: 175px;
  max-width: 100%;
  border: dotted 2px;
}
<div id="container">
  <div class="text-div">
      Short Text
  </div>

  <div class="text-div">
      Loooooooooooooog Text
  </div>
</div>

Upvotes: 1

Views: 1747

Answers (2)

Jeffhowcodes
Jeffhowcodes

Reputation: 416

Here is how you could achieve the desired result by adding some Javascript.

document.querySelectorAll('.text-div').forEach( div => {
  if(div.clientWidth > 175){
    div.classList.add('long-text');
  }else{
    div.classList.add('short-text');
  }
})
.text-div {
  display: table;
  border: dotted 2px;
}
.short-text{
  width: 175px;
}
.long-text{
  width: 100%
}
<div id="container">
  <div class="text-div">
      Short Text
  </div>

  <div class="text-div">
      Looooooooooooooooooooooooong Text
  </div>
</div>

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 272909

A hacky approximation using clamp(). You need an extra wrapper that has a shrink-to-fit behavior (I used float but you can consider inline-block). 100% of the child width will refer to its own width since its parent is shrink-to-fit.

I use clamp and compare 100% with 175px.

If 100% > 175px we have (100% - 175px)*10000 a big positive value clamped to 100vw, your full width behavior (we have to hide the overflow)

If 100% < 175px we have (100% - 175px)*10000 a big negative value clamped to 175px

#container {
  overflow:hidden;
}

.text-div {
  width: clamp(175px, (100% - 175px)*10000, 100vw);
  background:yellow;
  margin:5px;
}

.wrap {
  float: left;
  clear: left;
}
<div id="container">
  <div class="wrap">
    <div class="text-div">
      Short Text
    </div>
  </div>
  <div class="wrap">
    <div class="text-div">
      Looooooooooooooooooooooooooong Text
    </div>
  </div>
</div>

Upvotes: 2

Related Questions