Manos Kounelakis
Manos Kounelakis

Reputation: 3161

Centerize materializecss icon

I have a bin icon which I want to make it appear in the center of a container.I have tried text-align center and vertical-align:middle. However no matter what I do the icon seems to be a litte bit to the right side.

Here is a snippet

.container{
  border:4px solid blue;
}
i{
  margin-left:50%;
  margin-right:50%;
  text-align:center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>

<div class='container'>
  <i class='material-icons large'>delete</i>
</div>

Any Ideas how can I fix that?

Upvotes: 0

Views: 313

Answers (2)

Berdesdan
Berdesdan

Reputation: 359

When you set the margin-left:50%; you aren't taking the width of the icon into account. So the icon display starts in the middle and then 'adds' its width from there.

.container{
  border:4px solid blue;
}
i{
  margin-left:50%;
  transform: translateX(-50%);
  text-align:center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>

<div class='container'>
  <i class='material-icons large'>delete</i>
</div>

Another solution is to text-align:center; the .container css surrounding the <i class="material-icons large"> and remove the margin and text-align from the i css.

.container{
  border:4px solid blue;
  text-align: center;
}
i{

}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>

<div class='container'>
  <i class='material-icons large'>delete</i>
</div>

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42304

The problem is that you're setting margin-left and margin-right to 50%, while not accounting for the width of the icon itself. As the icon is 84px wide, you can centralise it by dividing 84px by 2, and then subtracting this value (42px) from each of your margins.

You can do this dynamically by making use of CSS' calc() method, as can be seen in the following:

.container {
  border: 4px solid blue;
}

i {
  margin-left: calc(50% - (84px / 2));
  margin-right: calc(50% - (84px / 2));
  text-align: center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />

<div class='container'>
  <i class='material-icons large'>delete</i>
</div>

Hope this helps! :)

Upvotes: 2

Related Questions