Search code examples
htmlcsshtml-tablelinetext-align

Break long text without spaces inside table cell


I would like to align this text like here but if I run this code, my longer text is in one line and text "My Informations is in two lines. How to align to more line with limited width?

<html>
<head>
<style>

.div_name p{
    position: fixed;
    display:inline;
}

.div_city p{
    display:inline;
}

.div_info p{
    display:inline;
} 

 div.all_info {
  position: absolute;
  right: 30%;
  width: 200px;
  height: 100px;
  //border: 3px solid blue;
} 
</style>

</head>
<body>

<div class="all_info" align = "right"> 
<table>
<tr><td align="right" width150px><div class="div_name:">Your name: </td> <td align="left" width=200px><p id="myname">David</p></td></div></tr>  
<tr><td align="right" width=150px><div class="div_city:">Your city: </td> <td align="left" width=200px><p id="mycity">Prageu</p></td></div></tr>
<tr><td align="right" width=250px><div class="div_info:">Your Informations: </td> <td align="left" width=200px><p id="myinfo">myinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfo</p></td></div></tr>
</table>    
</div>
</body>
</html>

Solution

  • The secret is to use word-break:break-all on each <td> cell.

    Alternatively you can use overflow-wrap but behaves similar.

    Note: In contrast to word-break, overflow-wrap will only create a break if an entire word cannot be placed on its own line without overflowing.

    Here's a thorough article comparing them both

    table{
      width: 400px;
      border: 1px dashed salmon;
    }
    
    table td{ 
      vertical-align: top; 
      padding: 5px;
      word-break: break-all;  /* MUST ADD THIS */
    }
    
    table td:nth-child(1){
      text-align: right;
      width: 140px;
    }
    <table>
      <tr>
        <td>Your name: 
        <td>David
      </tr>
      <tr>
        <td>Your city: 
        <td>Prageu
      </tr>
      <tr>
        <td>Your Informations: 
        <td>myinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfomyinfo
      </tr>
    </table>

    I've cleaned up your HTML markup, no need for wrapping div and p tags inside your table cells.