0

Take this code for example

.test {
  width: 50%;
  height: 50%;
}
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1 class="test">This is a Headindfdfdfdfdsdfsdffdfdfdfddfdfdfddfghfghfddfdfdfdfdfdfdfdfdfdffdffdfdffdg</h1>

</body>
</html>

I restrict the width of the heading to be half of the whole page, and I wish the text could automatically line breaking once it reaches out of the margin. But it doesn't work.

So, how to automatically (not using </br>) line breaking a heading ?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
null
  • 1,167
  • 1
  • 12
  • 30

2 Answers2

1

Add the rule word-break:break-word;

.test {
  width: 50%;
  height: 50%;
  word-break:break-word;
}
<html>

<head>
  <title>Page Title</title>
</head>

<body>

  <h1 class="test">This is a Headindfdfdfdfdsdfsdffdfdfdfddfdfdfddfghfghfddfdfdfdfdfdfdfdfdfdffdffdfdffdg</h1>

</body>

</html>

Note that there's also overflow-wrap which can be used.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Thank you. But how do you know about this? I tried to google `html heading line break` but got nothing useful. – null Jul 18 '19 at 18:28
  • 1
    @NathanExplosion 20+ years of experience ;) – j08691 Jul 18 '19 at 18:29
  • But actually, I find that the line break for a word does not give you a hyphen. How to enable a hyphen? – null Jul 19 '19 at 17:29
  • @NathanExplosion That's a different question and for that, see https://stackoverflow.com/questions/15261605/how-to-use-automatic-css-hyphens-with-word-break-break-all – j08691 Jul 19 '19 at 18:48
0

use css word-wrap

.test {
  width: 50%;
  height: 50%;
  word-wrap: break-word;
}
<h1 class="test">This is a Headindfdfdfdfdsdfsdffdfdfdfddfdfdfddfghfghfddfdfdfdfdfdfdfdfdfdffdffdfdffdg</h1>
sdn404
  • 614
  • 5
  • 7