html - 将两个 div 在 flex 容器中水平居中

标签 html css flexbox

我有两个 div(一个在另一个下面),我希望此列居中对齐。但使用 justify-content: center 时,div 沿 y 轴(垂直)居中对齐,而不是沿 x 轴(水平)居中对齐。

我想知道(使用 flexbox)沿 x 轴居中对齐的唯一方法是否是添加 margin: auto

<div id="sharesocial">
  <div id="sharecondividi">
    Condividi
  </div>
  <div id="shareicons">
    <a target="blank" href=""><span class="fa fa-twitter-square" id="twitterbt"></span></a>
    <a target="blank" href=""><span class="fa fa-google-plus-square" id="googleplusbt"></span></a>
    <a target="blank" href=""><span class="fa fa-facebook-square" id="facebookbt"></span></a>
  </div>
</div>

CSS

#sharesocial {
 background: #646464 none repeat scroll 0 0;
 border-radius: 10px;
 display: flex;
 flex-direction: column;
 height: 100px;
 justify-content: center;
 width: 174px;
}

#sharecondividi {
 align-self: center;
 color: #fff;
 display: flex;
 text-align: center;
}

#shareicons {
 align-items: center;
 background: #f0f0f0 none repeat scroll 0 0;
 border-radius: 5px;
 display: flex;
 height: 50%;
 justify-content: space-around;
 width: 95%;
}

这里是 jsfiddle:

https://jsfiddle.net/uLah0gqa/

最佳答案

flex-directioncolumn 时,您可以使用 justify-content 进行垂直对齐 align-items 用于水平对齐

试试这个:

#sharesocial {
    align-items: center;
}

Revised Demo

了解更多:

关于html - 将两个 div 在 flex 容器中水平居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35413879/

相关文章:

html - FlexBox 对齐元素

HTML 在调整窗口大小时改变位置

html - 在 iframe 顶部重叠 div

html - 如何修复框中的中心选择文本?

CSS 条纹与边框图像

javascript - 我怎样才能使这个活跃的点击?

css - 如何将 css 应用于在 alfresco web 快速入门中创建的自定义内容

css - 在 ie11 中使用 flexbox 在图像下方留空

javascript - 防止在隐藏和显示时推送元素 - jQuery

html - 可滚动div占用剩余高度(Bootstrap 4 Flexbox网格系统)