【问题标题】:How to display icon and text below each other with icon in center如何在中间显示图标和文本
【发布时间】:2021-01-13 18:49:19
【问题描述】:

我有一个带有背景图像的i 标签,然后跟随<span>。 基本上它是一个图标,后跟文本。我正在尝试将图标居中对齐,然后在图标下方对齐文本。 我该怎么做?

我尝试了垂直对齐,但它不起作用。

<li> 
<i class="icons" ></i>
<span>Icon text</span>
<li />

CSS:

.icons ::before {
content: url(/Style/Image1.svg);
}

【问题讨论】:

  • 仅供参考,您有一些错别字。你不能在班级和:before::before 之间有空格(我看到你在我打字时将其更改为使用::,但两种方式都很好)另外&lt;li /&gt; 也不正确

标签: css alignment vertical-alignment


【解决方案1】:

您可以通过几种方式做到这一点(一旦您修复了语法错误):

1.使用弹性盒
使用 flex,您只需要使用正确的选项来设置容器元素的样式,以使子元素按照我们的意愿行事 - 请参阅 cmets:

li {
  display: flex;
  align-items: center;     /* center align the elements in the container */
  flex-direction: column;  /* make the child elements appear one under another */
}

.icons:before {  content: url(https://via.placeholder.com/200x100); }
<ul>
  <li><i class="icons"></i><span>Icon text 1</span></li>
  <li><i class="icons"></i><span>Icon text 2</span></li>
</ul>

2。带有 text-align: center 的块元素

/* center-align the container element */
li { text-align: center; list-style: none; }

/* make i and span  block elements so they appear one below the other */
li i, li.span { display: block; }

.icons:before { content: url(https://via.placeholder.com/200x100); }
<ul>
  <li><i class="icons"></i><span>Icon text 1</span></li>
  <li><i class="icons"></i><span>Icon text 2</span></li>
</ul>

注意 - 您还有许多语法错误:

  • 选择器和:before(或::before - 两者都可以)之间不能有空格
  • 另外&lt;li /&gt; 也不正确 - 您使用&lt;/li&gt; 关闭li 元素

【讨论】:

    【解决方案2】:

    如您所见,您写的第一个错误是.icon 而不是.icons,第二个只是使用双精度::

    .icons::before {
    content: url("https://placeholder.pics/svg/300");
    }
    <i class="icons" ></i>
    <span>Icon text</span>

    【讨论】:

      【解决方案3】:

      将它们打包成如下样式的 div:

      <div style="text-align: center;">
          <i class="icons" ></i>
          <div>Icon text</div>
      </div>
      

      垂直对齐有效,当你想将它们放在一行中时,但如果我理解得很好,你想把文本放在图标下,所以你应该使用 text-align 而不是 vertical-align

      【讨论】:

        【解决方案4】:

        这里有一个更简单的方法

        .icons {
            display: flex;
            align-items: center;
        }
        
        .icons::before {
            content: url(https://static2.clutch.co/s3fs-public/logos/r7q9_xgp.png);
        }
        <li>
           <span class="icons">Icon Text here</span>
        </li>

        【讨论】:

          猜你喜欢
          • 2020-09-05
          • 2018-10-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多