OiO.lk Blog HTML center div with text doesn't work when viewport gets narrow
HTML

center div with text doesn't work when viewport gets narrow


I have a div (.quote) in which another div (.centered) should be centered inside the viewport (here simulated with anohter div). The text inside .centered should be left-aligned. The text has some predefined linebreaks, but should break on other words as well if necessary.

.viewport {
  width: 440px;
  border: 1px solid red;
}

.quote {
  display: flex;
  flex-direction: row;
  justify-content: center;
  }
  
  .txt {
    font-size: 64px;
  }
<div class="viewport">
  <div class="quote">
    <div class="centered">      
      <span class="txt">This is a long text, with a<br>predefined linebreak</span>
      <br>
      <span class="author">It's me</span>
    </div>
  </div>
 </div>

This works fine as long as the viewport is wide enough (delete width in class viewport):

But as soon as it gets narrow, the div.centered isn’t centered anymore (set viewport.width to 440px):

As you can see, the text is now suddenly left aligned, leaving a space on the right side.

What might be the problem and how can I get rid of it?

Edit: This is would I would have expected:



You need to sign in to view this answers

Exit mobile version