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

html - How to Center and Right-align on a row with CSS Flex only

Tried many variations like this, but could not get it to work. Here is the last attempt:

.parent {
  display: flex;
  //justify-content: center;
  width: 600px;
  background-color: yellow
}
.c {
  //flex: 1 1 0;
  //text-align: end;
  margin-left: auto;
  margin-right: auto;
  background-color: cyan;
}  
.e {
  //flex: 1 1 0;
  // text-align: end;
  background-color: grey;
}  
.bs {
  background-color: green;
  color: white;
  width: 70px;
}

with html:

<div class="parent">
  <div class="c">
    <button class="bs">OK</button>
    <button class="bs">Cancel</button>
  </div>
  <div class="e">
    <button class="bs">Help</button>
  </div>
</div>

I know how to solve this by placing a 'visibility: hidden' button on the left-hand side and use justify-content with space-between, but I want to learn/know how to do it using CSS only.

Would be grateful for advice.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There is more than one way to do that.

Here with CSS only (no extra markup/hidden element) using a pseudo and make it and each button wrapper take 1/3 each of the total width, by giving them flex-basis: 100% and then the default flex-shrink: 1 will shrink them equally.

.parent {
  display: flex;
  width: 600px;
  background-color: yellow
}
.parent::before, .c, .e {
  content: '';
  flex-basis: 100%;
}
.c {
  background-color: cyan;
  text-align: center;
}  
.e {
  background-color: grey;
  text-align: right;
}  
.bs {
  background-color: green;
  color: white;
  width: 70px;
}
<div class="parent">
  <div class="c">
    <button class="bs">OK</button>
    <button class="bs">Cancel</button>
  </div>
  <div class="e">
    <button class="bs">Help</button>
  </div>
</div>

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

...