如何将内部元素水平居中" scoreBox"?

时间:2017-08-18 16:48:42

标签: html css css3 flexbox

如何将元素水平居中于" scoreBox" ?

他们目前只是左对齐。



.voteButtons {
  display: inline-block;
  text-align: center;
}

.HP {
  display: inline-block;
  text-align: center;
  width: auto !important;
  margin-left: 5px !important;
}

.scoreBox {
  display: flex;
  margin-top: 10px;
  padding-top: 10px;
  text-align: center;
  width: auto !important;
}

<div class="scoreBox">
  <span class="voteButtons"><img class="UpvoteButton" id="voteUp" src="..."><img class="DownvoteButton" id="voteDown" src="..."></span>
  <div class="HP">
    <%= post.upvotes - post.downvotes%> score </div>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

justify-content: center添加到您的scoreBox - 请参阅下面的演示:

.voteButtons {
  display: inline-block;
  text-align: center;
}

.HP {
  display: inline-block;
  text-align: center;
  width: auto !important;
  margin-left: 5px !important;
}

.scoreBox {
  display: flex;
  margin-top: 10px;
  padding-top: 10px;
  text-align: center;
  width: auto !important;
  justify-content: center;
}
<div class="scoreBox">
  <span class="voteButtons"><img class="UpvoteButton" id="voteUp" src="..."><img class="DownvoteButton" id="voteDown" src="..."></span>
  <div class="HP">
    <%= post.upvotes - post.downvotes%> score </div>
</div>

答案 1 :(得分:2)

制作HP width: 100%margin: 0 auto 发生这种情况是因为你无法居中对齐整个div,所以如果你想要宽度100%,你需要做一些边缘魔术。

编辑:对齐内容也很有意义

.voteButtons {
  display: inline-block;
  text-align: center;
}

.HP {
  display: inline-block;
  text-align: center;
  width: auto !important;
  margin: 0 auto;
}

.scoreBox {
  display: flex;
  margin-top: 10px;
  padding-top: 10px;
  text-align: center;
  width: auto !important;
}
<div class="scoreBox">
  <span class="voteButtons"><img class="UpvoteButton" id="voteUp" src="..."><img class="DownvoteButton" id="voteDown" src="..."></span>
  <div class="HP">
    <%= post.upvotes - post.downvotes%> score </div>
</div>

答案 2 :(得分:1)

从下面的代码中可以看出,我只是添加了对齐内容并使其成为中心。它定义了沿主轴的对齐方式。当线路上的所有弹性项目都不灵活,或者灵活但已达到最大尺寸时,它将帮助您分配剩余的额外空间。

当物品溢出线时,它还会对物品的对齐施加一些控制。

轻松了解如何使用justify-content look this image that I got it a while a go online的不同方式。

希望这会回答你的问题。

&#13;
&#13;
.voteButtons {
  display: inline-block;
  text-align: center;
}

.HP {
  display: inline-block;
  text-align: center;
  width: auto !important;
  margin-left: 5px !important;
}

.scoreBox {
  display: flex;
  margin-top: 10px;
  padding-top: 10px;
  text-align: center;
  width: auto !important;
  justify-content: center;
}
&#13;
<div class="scoreBox">
  <span class="voteButtons"><img class="UpvoteButton" id="voteUp" src="..."><img class="DownvoteButton" id="voteDown" src="..."></span>
  <div class="HP">
    <%= post.upvotes - post.downvotes%> score </div>
</div>
&#13;
&#13;
&#13;