Search code examples
htmlcssalignment

How to center align an overflowing element in CSS


I have a box with text-align: center, with a max-width: 420px. Inside the box there is a h1 with a very long word. (See the code example)

The Problem: The overflowing word is now left aligned. I know, there is word-wrap for this, but I dont want to cut the text, it has to be on the same line. The width of the box is also fixed and can not be more.

My question: Is it possible to center align the big overflowing word?

.titles {
  text-align: center;
  padding: 3rem 0;
  margin: 0 auto;
  max-width: 420px;
  background: lightgrey;
}

h1 {
  font-size: 2.9rem;
  margin: 0 0 1.9rem;
  color: #3d78c7;
  font-weight: 700;
  line-height: 1.2;
}
<div class="titles">
  <h1>Allgemeine Geschäftsbedingungen</h1>
</div>


Solution

  • I will answer this for now, but I think it may be a duplicate. If one is found, I will delete the answer.

    You can do this by making the <h1> element a flex item and using justify-content: center; on it.

    .titles {
      text-align: center;
      padding: 3rem 0;
      margin: 0 auto;
      max-width: 420px;
      background: lightgrey;
    }
    
    h1 {
      font-size: 2.9rem;
      margin: 0 0 1.9rem;
      color: #3d78c7;
      font-weight: 700;
      line-height: 1.2;
      display: flex;
      justify-content: center;
    }
    <div class="titles">
      <h1>Allgemeine Geschäftsbedingungen</h1>
    </div>