Search code examples
htmlcsscenteringword-wrap

Center div on wrapping (when it doesn't fit on the line)


I am trying to create this layout using only CSS:

When title fits:

sketch 1

When title doesn't fit:

sketch 2

The btn on the right should be centered if it wraps.


I tried this:

.container {
    width: 100%;
    border: 1px solid grey;
    padding: 5px;
}
.block {
    padding: 5px;
    border: 1px solid orange;
    float: left;
}
.right-block {
    float: right;
}
<div class="container">
    <div class="block">Logo</div>
    <div class="block">Title that is too long</div>
    <div class="block right-block">right-btn</div>
    <div style="clear: both"></div>
</div>

But obviously, the btn is still on the right after it wraps. Any idea how to center it when it wraps ? And I'd like to avoid javascript.

Fiddle here: http://jsfiddle.net/b7rvhwqg/


Solution

  • Pure CSS solution using a flexbox layout:

    Updated Example Here

    The trick is to add justify-content: center/flex-wrap: wrap to the parent .container element for horizontal centering. Then adjust the first element's margin-right value to auto in order to prevent the last element from being centered when it's on the same line.

    (You may need to resize the browser to see how it adjusts).

    .container {
      width: 100%;
      border: 1px solid grey;
      padding: 5px;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
    }
    .logo-text {
      display: flex;
      margin-right: auto;
    }
    .block {
      padding: 5px;
      border: 1px solid orange;
    }
    .center-block {
      white-space: nowrap;
      margin-right: auto;
    }
    <div class="container">
      <div class="logo-text">
        <div class="block logo">Logo</div>
        <div class="block text">This title is short.</div>
      </div>
      <div class="block right-block">right-btn</div>
    </div>
    <div class="container">
      <div class="logo-text">
        <div class="block logo">Logo</div>
        <div class="block text">This title is slightly longer than the other one. This title is longer than the other one...</div>
      </div>
      <div class="block right-block">right-btn</div>
    </div>