Align list items with a single font awesome icon

我怕爱的太早我们不能终老 提交于 2020-01-05 10:18:26

问题


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

回答1:


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>



回答2:


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.




回答3:


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>


来源:https://stackoverflow.com/questions/34724451/align-list-items-with-a-single-font-awesome-icon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!