尽管使用了display:flex,为什么这两个元素会垂直偏移?

时间:2017-11-29 11:47:03

标签: html css css3 flexbox

我希望文字和图标都完全垂直居中,如下所示:

Screen correct

这就是我将display:flex用于align-items:center的原因,但我得到的是:

Screen fail

代码

注意:我使用的是React,所以请注意内联样式: - )

<div style="background-color:#999;position:fixed;width:100%;height:52px;box-shadow:0 -12px 27px #999;display:flex;align-items:center">
   <div style="flex:1;height:24px;margin-left:20px">
      <div style="display:inline-block;width:24px;height:24px;border: 1px solid green;">
         <img style="width:100%;height:100%;border:0" src="https://t3.ftcdn.net/jpg/00/63/33/38/240_F_63333813_qO48nGh5uFZ0EVkCYS3ZehhrR10dWg4D.jpg" alt="Logo">
      </div>
      <h1 style="display:inline-block;margin:0;text-transform:uppercase;font-family:Raleway, serif;font-weight:900;font-size:18px;height:24px;border: 1px solid red;">MyLogo</h1>
   </div>
</div>

https://codepen.io/valnub/pen/XzxOvY

出了什么问题?我不明白:-(请帮助我,哦强大的flexbox css大师!

1 个答案:

答案 0 :(得分:2)

您正在设置外部容器以显示:flex,但不是内部容器。添加display:flex to that应解决您的问题:

<div style="background-color:#999;position:fixed;width:100%;height:52px;box-shadow:0 -12px 27px #999;display:flex;align-items:center">
   <div style="display: flex;flex:1;height:24px;margin-left:20px">
      <div style="display:inline-block;width:24px;height:24px;border: 1px solid green;"><img style="width:100%;height:100%;border:0" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=" alt="Logo"></div>
      <h1 style="display:inline-block;margin:0;text-transform:uppercase;font-family:Raleway, serif;font-weight:900;font-size:18px;height:24px;border: 1px solid red;">MyLogo</h1>
   </div>
</div>

https://codepen.io/anon/pen/wPYOed