White space nowrap but break line if greater than max width in css

Viewed 1129

I use white-space: nowrap so my string will stay in one line but I also set max-width: 100px because I want the string to break only when over the max-width, makes sense only the two parameters conflicts each other. The white-space property "overpower" the max-width property and the string stay in one line.

<div class="mydiv">this is my text</div>
.mydiv {
  position: absolute;
  white-space: nowrap;
  max-width: 100px;
  left: 50%;
  transform: translateX(-50%);
}

I tried "playing" with overflow-wrap property but that didn't work either.

If I remove the white-space property, the string break word by word, each word in a new line. That's happening because the element is position: absolute, I think..

So how do I solve this?

1 Answers

If I remove the white-space property, the string break word by word, each word in a new line. That's happening because the element is position: absolute, I think

It happens because of the left:50% that will restrict the width of your element to a maximum width equal to 50% of the containing block width.

Add a negative margin-right to avoid this issue

.mydiv {
  position: absolute;
  max-width: 400px;
  left: 50%;
  transform: translateX(-50%);
  margin-right:-50%;
  border:1px solid;
}
<div class="mydiv">this is my text this is my text this is my text this is my text this is my text</div>

Without the margin trick the item will wrap sooner:

.mydiv {
  position: absolute;
  max-width: 400px;
  left: 50%;
  transform: translateX(-50%);
  border:1px solid;
}
<div class="mydiv">this is my text this is my text this is my text this is my text this is my text</div>

Related