首页 > 解决方案 > 使用 flex 将图标与文本水平对齐

问题描述

努力将我的图标与标题水平对齐(标题上方 50%/下方 50%) - 下面可能并不能完全表明问题,因为添加了红色填充,但我使用的图标有点额外空间顶部和底部,所以它看起来像它坐在下面。将 StyledComponents 与 React 一起使用,但下面的代码片段复制了该问题。

.accordion {
  background-color: #e5e9eb;
  height: 174px;
  max-width: 612px;
  border-radius: 2px;
  border: 1px solid #27282a;
  margin-bottom: 48px;  
}

.title {
  font-size: 0.75rem;
  letter-spacing: 0.063rem;
  text-transform: uppercase;
  padding-left: 24px;
  padding-top: 20px;
  padding-bottom: 0px;
}

.icon {
  background-color: red;
  height: 40px;
  width: 40px;
  float: right;
  margin-right: 12px;
}

.span {
  line-height: 1.25rem;
  padding-left: 24px;
  padding-right: 24px;
  display: block;
}
<div class="accordion">
  <h3 class="title">TEXT THAT SHOULD BE LEVEL WITH ICON
    <div class="icon"></div>
  </h3>
  <span class="span">Icon should be horizontally level with title text</span>
</div>

在此处输入图像描述

标签: htmlcssflexbox

解决方案


检查下面的片段。

.accordion {
  background-color: #e5e9eb;
  height: 174px;
  max-width: 612px;
  border-radius: 2px;
  border: 1px solid #27282a;
  margin-bottom: 48px;  
}

.title {
  font-size: 0.75rem;
  letter-spacing: 0.063rem;
  text-transform: uppercase;
  padding-left: 24px;
  padding-top: 20px;
  padding-bottom: 0px;
  display: flex;
  align-items: center;
}

.title span {
  flex: 1;
}

.icon {
  background-color: red;
  height: 40px;
  width: 40px;
  float: right;
  margin-right: 12px;
}

.span {
  line-height: 1.25rem;
  padding-left: 24px;
  padding-right: 24px;
  display: block;
}
<div class="accordion">
  <h3 class="title">
    <span>TEXT THAT SHOULD BE LEVEL WITH ICON</span>
    <div class="icon"></div>
  </h3>
  <span class="span">Icon should be horizontally level with title text</span>
</div>


推荐阅读