Michiel Borkent Michiel Borkent - 4 days ago 4
CSS Question

Align icons with text without using a negative margin

I'm looking for a more elegant way to align the right icons with the left text vertically, as the negative margin might be a little bit of a hack.



div.main {
border: 1px solid black;
padding: 14px;
}

div.icons {
margin-top: -1.65em;
}

div.icon {
font-size: 2rem;
color: blue;
border: 0.1px solid blue;
border-radius: 3px;
margin-left: -1px;
padding: 3px;
float: right;
}

<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
</head>

<body>

<div class="main">
<div class="summary">Some text</div>
<div class="icons pull-right">
<div class="icon fa fa-line-chart">
</div>
<div class="icon fa fa-bar-chart">
</div>
</div>
</div>

</body>
</html>




Answer

You can use CSS Flexbox. And use flex's align properties. Have a look at the snippet below:

div.main {
  border: 1px solid black;
  padding: 14px;
  display: flex;
  align-items: center;
}

div.summary {
  flex: 1;
}

div.icon {
  font-size: 2rem;
  color: blue;
  border: 0.1px solid blue;
  border-radius: 3px;
  margin-left: -1px;
  padding: 3px; 
  float: right;
}
<html>
<head>  
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>  
</head>

<body>
  
  <div class="main">
  <div class="summary">Some text</div>
  <div class="icons">
    <div class="icon fa fa-line-chart">
    </div>
    <div class="icon fa fa-bar-chart">
    </div>
  </div>
</div>
  
</body>
</html>

Hope this helps!

Comments