Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

css - Align 3 unequal blocks left, center and right

I'm trying to align a top menu which consists of 3 blocks of content.

What I'm trying to achieve is this:

  • block 1: left aligned
  • block 2: centered horizontally
  • block 3: right aligned

If all 3 blocks were the same size, I could use flexbox (as in the snippet), but they're not, so it doesn't produce the output I require.

Instead, flexbox puts equal space between the 3 blocks - resulting in the middle block being aligned off-center.

I was wondering if this could be achieved with flexbox, or if not, another solution. This needs to work robustly in production so a 'Grid' solution is not applicable as there is insufficient support.

.container {
  margin: 20px 0;
}

.row {
  background-color: lime;
  display: flex;
  justify-content: space-between;
}

.item {
  background-color: blue;
  color: #fff;
  padding: 16px;
}
<div class="container">
  <div class="row">
    <div class="item">left, slightly longer</div>
    <div class="item">center, this item is much longer</div>
    <div class="item">right</div>
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can consider flex-grow:1;flex-basis:0% for the left and right elements then use text-align to align content inside. I have added an extra wrapper to keep the background only around the text.

The trick is to calculate the free space by removing only the middle content and split it equally to the left and right element.

.container {
  margin: 20px 0;
  padding-top:10px;
  background:linear-gradient(#000,#000) center/5px 100% no-repeat; /*the center*/
}

.row {
  background-color: lime;
  display: flex;
  color: #fff;
}

.item:not(:nth-child(2)) {
  flex-basis: 0%;
  flex-grow: 1;
}

.item:last-child {
  text-align: right;
}

.item span{
  background-color: blue;
  display:inline-block;
  padding: 16px;
  border: 2px solid red;
  box-sizing:border-box;
}
<div class="container">
  <div class="row">
    <div class="item"><span>left, slightly longer</span></div>
    <div class="item"><span>center, this item is much longer</span></div>
    <div class="item"><span>right</span></div>
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...