How to Make the Middle Item Stay Centered

Solution with Flexbox

It is possible to center the middle item regardless of the widths of siblings by using Flexbox. You need to use nested flex containers and auto margins.

Below, you can see how it can be done.

Example of making the middle item stay centered:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .container {
        display: flex;
      }
      .box {
        flex: 1;
        display: flex;
        justify-content: center;
      }
      .box:first-child > span {
        margin-right: auto;
      }
      .box:last-child > span {
        margin-left: auto;
      }
      .box {
        align-items: center;
        border: 1px solid #666;
        background-color: #c8cbcf;
        height: 60px;
      }
      p {
        text-align: center;
        margin: 5px 0 0 0;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="box">
        <span>short text</span>
      </div>
      <div class="box">
        <span>centered text</span>
      </div>
      <div class="box">
        <span>loooooooooooooong text</span>
      </div>
    </div>
  </body>
</html>

Result

short text
centered text
loooooooooooooong text

Here, the <div> with the class name "container" is a flex container, and child <div> elements with class names “box” are flex items. We set the flex property for each child element to 1 to distribute the container space equally. This makes the items use all space in the row and have equal width. Then, we make each item a nested flex container and use the justify-content property with the “center” value. The margin-right and margin-left properties with the “auto” values are used to move the outer <span> elements to the right and left, respectively.

This solution does not allow to specify the width.