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
458 views
in Technique[技术] by (71.8m points)

html - Aligning elements left and center with flexbox

I'm using flexbox to align my child elements. What I'd like to do is center one element and leave the other aligned to the very left. Normally I would just set the left element using margin-right: auto. The problem is that pushes the center element off center. Is this possible without using absolute positioning?

HTML & CSS

#parent {
  align-items: center;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  width: 500px;
}
#left {
  margin-right: auto;
}
#center {
  margin: auto;
}
<div id="parent">
  <span id="left">Left</span>
  <span id="center">Center</span>
</div>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Add third empty element:

<div class="parent">
  <div class="left">Left</div>
  <div class="center">Center</div>
  <div class="right"></div>
</div>

And the following style:

.parent {
  display: flex;
}
.left, .right {
  flex: 1;
}

Only left and right are set to grow and thanks to the facts that...

  • there are only two growing elements (doesn't matter if empty) and
  • that both get same widths (they'll evenly distribute the available space)

...center element will always be perfectly centered.

This is much better than accepted answer in my opinion because you do not have to copy left content to right and hide it to get same width for both sides, it just magically happens (flexbox is magical).


In action:

.parent {
  display: flex;
}

.left,
.right {
  flex: 1;
}


/* Styles for demonstration */
.parent {
  padding: 5px;
  border: 2px solid #000;
}
.left,
.right {
  padding: 3px;
  border: 2px solid red;
}
.center {
  margin: 0 3px;
  padding: 3px;
  border: 2px solid blue;
}
<div class="parent">
  <div class="left">Left</div>
  <div class="center">Center</div>
  <div class="right"></div>
</div>

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

...