简体   繁体   中英

Align list items with a single font awesome icon

How can I properly align my <li> with a single Font Awesome icon and without using nth-child as the tag will be dynamic?

https://jsfiddle.net/wt7hsdgq/

 ul { list-style: none; } li { padding-left: 5px; } 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <ul> <li><i class="fa fa-tag"></i> <a href="#">#Jobs</a></li> <li><a href="#">#Interview</a></li> </ul> 

What I want is basically something like this:

[fa] #Jobs
     #Interview

Use pseudo element :before for the icon.

 ul { list-style: none; } li { padding-left: 5px; } li:before { content: ""; display: inline-block; width: 20px; } li:first-child:before { font-family: "FontAwesome"; content: "\\f02b"; } 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <ul> <li><a href="#">#Jobs</a></li> <li><a href="#">#Interview</a></li> </ul> 

I'm not fond of this technique, but it is sometimes useful : you can put a bigger padding-left on all the li and a negative margin-left on the class fa .

CSS

ul {
  list-style: none;
}
li {
  padding-left: 30px;
}
li .fa {
  margin-left: -18px;
}

HTML

<ul>
  <li>
    <i class="fa fa-tag"></i>
    <a href="#">#Jobs</a>
  </li>
  <li>
    <a href="#">#Interview</a>
  </li>
  <li>
    <a href="#">#AnotherOneWithoutTag</a>
  </li>
  <li>
    <i class="fa fa-tag"></i>
    <a href="#">#AnotherOneWithTag</a>
  </li>
</ul>

Doing this, you don't have to care about the presence or not of an icon.

Try to add a class to every li that dont have the font awesome, like this;

<li><a class="noFontAwesome" href="#">#Interview</a></li>

http://jsfiddle.net/wt7hsdgq/2/

Or use this snippet:

 ul { list-style: none; } li { padding-left: 5px; } li .fontAwesome:before { font-family: "FontAwesome"; content: "\\f02b"; margin-right: 5px; margin-left: -1.3em; } 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <ul> <li><a class="fontAwesome" href="#">#Jobs</a></li> <li><a href="#">#Interview</a></li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM