Home > Net >  Center text vertically and horizontally, which exceeds its own parent
Center text vertically and horizontally, which exceeds its own parent

Time:11-30

I have the following solution to center my text:

.close-button {
  margin-top: auto;
  padding: 0;
  cursor: pointer;
  border: none;
  border-radius: 5rem;
  background: black;
  color: white;
  position: relative;
  width: 5rem;
  height: 5rem;
  
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
}
<button class="close-button">
  <div class="mark"> </div>
</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

As you can see, the element is perfectly centered, I believe. However, when I add a big font-size the element containing text appears at random locations. See below:

Show code snippet

.close-button {
  margin-top: auto;
  padding: 0;
  cursor: pointer;
  border: none;
  border-radius: 5rem;
  background: black;
  color: white;
  position: relative;
  width: 5rem;
  height: 5rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  
  /*The line below is new*/
  font-size: 8rem;
}
<button class="close-button">
  <div class="mark"> </div>
</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Why is that and how can I fix that, so that the element is centered again?

CodePudding user response:

You can add :

align-items: center;

.close-button {
  margin-top: auto;
  padding: 0;
  cursor: pointer;
  border: none;
  border-radius: 5rem;
  background: black;
  color: white;
  position: relative;
  width: 5rem;
  height: 5rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  align-items: center;
  /*The line below is new*/
  font-size: 8rem;
}
<button class="close-button">
  <div class="mark"> </div>
</button>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

To be honest, to fully solve your issue (this one) and similar ones in future I advise you to read this article about whitespaces in HTML. Adding align-items: center; will solve the issue, but putting div inside button is semantically incorrect, source here. Hope this helps to solve your issue and you can easily find out why it occurred.

Happy coding!

  • Related