1

Is there a way to center a div horizontally as shown below?

enter image description here

Notice the dark gray button is exactly centered and the links on each side are aligned left or right against that centered button. The left and right links don't affect the centered button's 'centeredness'

I solved it here on CodePen in a way I don't think is best - by just setting the DIVs with links to the same pixel width. I don't prefer this as it is sort of relying on magic numbers. I also wonder if the width could use calc() and subtract half the width of the dark gray button - but calc() doesn't have full support and so I don't think this gets me much further than my current solution.

CSS I used in the CodePen link above:

  background-color: #ccc;
  display: flex;
  justify-content: center;
}

.top-head-links {
  display: flex;
  width: 1200px;
  justify-content: center;

  .top-head-left-links, .call-button, .top-head-right-links {
    padding: 1rem;
  }
  
  .top-head-left-links, .top-head-right-links {
    width: 400px;
  }
  
  .top-head-left-links {
    display: flex;
    justify-content: flex-end;
  }
  ul {
    margin: 0;
    padding: 0;
    display: flex;
    list-style: none;

    li {
      margin-right: 1rem;

      &:last-of-type {
        margin-right: 0;
      }
    }
  }
  
  .call-button {
    background-color: gray;
    display: inline-block;
    color: #fff;
  }
}

My question: Does Flexbox or Grid allow for centering the the dark gray button in this way?

I couldn't get the Flexbox - align-self: center; on the dark gray button to produce the effect shown in the screenshot above

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
stemlund
  • 41
  • 1

0 Answers0