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

html - How to align groups of buttons on single row with Flex only?

I tried this:

<html>
<head>
<title>Left, Mid, Right action buttons</title>
<style>
.parent {
  width: 600px;
  background-color: yellow;
}
.itemleft {
  display: flex;
  justify-content: flex-start;
}
.itemcenter {
  display: flex;
  justify-content: center;
}
.itemright {
  display: flex;
  justify-content: flex-end;
}
.bs {
  background-color: green;
  color: white;
  width: 70px;
}
</style>
</head>
<body>
  <div class="parent">
    <span class="itemleft">
      <button class="bs">Edit</button>
      <button class="bs">Delete</button>
    </span>
    <span class="itemcenter">
      <button class="bs">OK</button>
      <button class="bs">Cancel</button>
    </span>
    <span class="itemright">
      <button class="bs">Help</button>
    </span>
  </div>
</body>
</html>

Result running this in Firefox or Chrome:

  • Edit and Delete buttons are left-justified on the row
  • OK and Cancel buttons are centered on NEXT 2nd row
  • Help button is right-justified on NEXT 3rd row

I expected all buttons on the same first row first since I used span. I got same result when replacing the spans with divs.

I also tried changing 'display: flex;' to 'display inline-flex;'. Then all buttons appeared together on one row, but the justification did not work. The buttons appeared one after the other with no spaces for justification.

Have I made some mistake in the html above? Is it possible to justify the button groups by Flex only? If yes, how?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

When one add display: flex to each item*, it is their content that be comes flex items, not the item* themselves.

Simply add display: flex; justify-content: space-between to the parent instead, and remove the flex properties from the item*

.parent {
  display: flex;
  justify-content: space-between;
  width: 600px;
  background-color: yellow;
}
.bs {
  background-color: green;
  color: white;
  width: 70px;
}
<div class="parent">
    <span class="itemleft">
      <button class="bs">Edit</button>
      <button class="bs">Delete</button>
    </span>
    <span class="itemcenter">
      <button class="bs">OK</button>
      <button class="bs">Cancel</button>
    </span>
    <span class="itemright">
      <button class="bs">Help</button>
    </span>
  </div>

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

...