Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...