angularangular-materialangular-material2

Angular-Material2: Align text and md-icon vertically to match vertical style?


I know I am probably missing something here. I am trying to align md-icon and some text vertically, right now the word "sample text" displays below the icon.

<div>
  <md-icon>home</md-icon> Sample Text
</div>

Output:

enter image description here

I did try playing around with vertical align on the Sample Text using a span but couldn't get anything working and felt kind of hacky anyway.

Anyone know how to get this effect?


Solution

  • This is a common issue when using <md-icon>. To align the icon and text, you can put your text inside a span and apply style to that:

    <div>
      <md-icon>home</md-icon><span class="aligned-with-icon">Sample Text</span>
    </div>
    

    In your component.css:

    .aligned-with-icon{
        position: absolute;
        margin-top: 5px;
        margin-left: 5px; /* optional */
    }
    

    You can also use relative position if you'll be putting multiple icons in the same div. Here is the css for that:

    .aligned-with-icon-relative{
        position: relative;
        top: -5px;
        margin-left: 5px; /* optional */
    }
    

    Another option is to use flex display on the outer div and align-items to center:

    In your html:

    <div class="with-icon">
      <md-icon>home</md-icon>Sample Text
    </div>
    

    In your css:

    .with-icon {
        display: flex;
        align-items: center;
    }
    

    Here is a Plunker Demo