SBB
SBB

Reputation: 8970

Bootstrap align icon to leftside of button

I have a bootstrap 3 button and it's using font awesome for the icons. I am trying to Center the text on the button but have the icon aligned to the left side.

<button type="button" class="btn btn-default btn-lg btn-block">
  <i class="fa fa-home pull-left"></i> Home
</button>

When I use pull-left, there is no padding or margin so the icon is too close to the edge (image 1).

enter image description here

However, when I try to add a margin-left or padding-left to the icon, its moving the text over to the right as well (should remain center).

enter image description here

Is there a way to not push the text over when using margins or padding on these icons?

Upvotes: 2

Views: 9786

Answers (2)

Jasper Mulder
Jasper Mulder

Reputation: 303

You use a pseudo-element to display the icon:

button::before{
	position: absolute;
	font-family: "Font Awesome 5 Free";
	display: inline-block;
	font-style: normal;
	font-variant: normal;
	text-rendering: auto;
	-webkit-font-smoothing: antialiased;
	font-weight: 900; 
	content: "\f015";
	left: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet"/>

<button type="button" class="btn btn-default btn-lg btn-block">Home</button>

Upvotes: 0

Hanif
Hanif

Reputation: 3797

Hmm please see the snippet it could solve your problem. Used position on new added class selector left-icon-holder.

.left-icon-holder {
    position:relative;
}
.left-icon-holder .fa {
    position:absolute;
    line-height: 24px;
    top:50%;
    margin-top: -12px; /* Half of line height to keep left middle postion of container */
    left: 10px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />

<button type="button" class="btn btn-default btn-lg btn-block left-icon-holder">
  <i class="fa fa-home"></i> Home
</button>

Upvotes: 6

Related Questions