简体   繁体   中英

CSS: Prevent text from overflowing div element

I'm using Bootstrap 4 and have a div which has long text inside it. If the text gets to long, it overflows my div .

It looks like this .

Adding a space (resulting in shorter words) results in it looking fine.

Long words like "hhhhhhhhhhhhhhhhhhh" will cause overflow, like it did in the picture.

My code:

 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" /> <div class="p-1 mt-4 d-flex flex-wrap"> <div class="p-1 m-1 d-flex flex-content-around shadow-lg p-2 mb-4 bg-white rounded box"> <div class="my-auto"> <img alt="pokemon pic" src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/66.png" /> </div> <div class="p-1 d-flex flex-column"> <div class="p-0"> <h3>Macgoooooo</h3> </div> <div class="p-0 d-flex flex-column flex-wrap"> <div class="p-0"> <span>cought at</span> </div> <div class="p-0"> <small>2019-09-01</small> </div> </div> </div> </div> </div> 

I would really like to know how to make the text fit inside the flexbox.

Use overflow-wrap: break-word; Docs like this:

 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" /> <div class="p-1 mt-4 d-flex flex-wrap"> <div class="p-1 m-1 d-flex flex-content-around shadow-lg p-2 mb-4 bg-white rounded box"> <div class="my-auto"> <img alt="pokemon pic" src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/66.png" /> </div> <div class="p-1 d-flex flex-column" style="display:inline-block; word-break: break-word;"> <div class="p-0"> <h3>Macgoooooo</h3> </div> <div class="p-0 d-flex flex-column flex-wrap"> <div class="p-0"> <span>cought at</span> </div> <div class="p-0"> <small>2019-09-01</small> </div> </div> </div> </div> </div> 

The code works perfectly fine, but still if there still is issue, then you should try the following to add in your css:

h3{
  word-break: break-all;
}

This will break any long words and will keep everything in multiple lines depending on the length of your word.

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

for the width attribute, you need to use the width of the box

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM