0

I have a div which is a square and stays a square regardless of the device. I need to place a FontAwesome icon inside this square and I need the icon to stay centered in all screens. For some reason I'm not achieving this.

In desktop it looks good, you can see the icon in horizontally and vertically centered:

enter image description here

In mobile it looks like the image below, the icon is no longer centered:

enter image description here

I would like to achieve this without using media queries. Here's my Codepen.

Paula
  • 477
  • 6
  • 20

3 Answers3

1

The reason why the icon isn't centered is because of two things:

You are trying to resize the container (<i>) of the actual vector graphic instead of the actual graphic (::before inside <i>). This moves the graphic to the right whenever its container gets smaller.

Font awesome is using unicode characters to display icons. They are basically text. To resize the graphic itself you can do this (the 2em value is an example):

.add-img-button::before {
  font-size: 2em;
}

You can use the transform: translate(-50%, -50%) option to move the anchor point of an element to its center and then position it using left: 50%, top: 50%.

.add-img-button {
  color: #8abe57;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 1.5em;
}
NakedCat
  • 852
  • 1
  • 11
  • 40
1

.img-holder {
  width: 240px;
  height: 240px;
  border: 2px dotted #8abe57;
  border-radius: 0.25rem;
  display: flex;
}

.img-holder i {
  margin: auto;
  font-size: 30px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet"/>
<div class="img-holder">
  <i class="fas fa-camera add-img-button"></i>
</div>
h3h394
  • 33
  • 1
0

Just change your .add-img-button like so

.add-img-button {
    color: #8abe57;
    position: absolute;
    /* width: 10%; */
    height: auto;
    display: inline-block;
    top: 50%;
    right: 50%;
    transform: translate(50%, -50%);
    font-size: 1.5em;
}

By removing the imposed width you can truly center it using top and right (or left) then use transfor translate to adjust to the center of the object.

here's a pen

JHeth
  • 7,067
  • 2
  • 23
  • 34