Search code examples
cssalignmentvertical-alignment

How to display icon and text below each other with icon in center


I have an i tag with background image and then follows <span>. Basically its an icon followed by text. I am trying to align the icon in center and then below the icon the text. How can I do this?

I tried with vertical align, but it did not work.

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

CSS :

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

Solution

  • You can do this a few ways (once you fix the syntax errors):

    1. Using flexbox
    With flex you only need to style the container element using the right options to make the child elements act as we wish - see the comments:

    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. Block elements with 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>

    Note - you also have a number of syntax errors:

    • You cannot have a space between the selector and :before (or ::before - both work)
    • Also <li /> is not correct - you close an li element using </li>