Home > OS >  How to center the text inside my :before pseudo element?
How to center the text inside my :before pseudo element?

Time:04-03

I have this custom bullet point type thing and I want to have the number centered inside a circle. I'm doing pretty good however I'm stuck at centering. I literally just want the text to go up by a couple pixels, why is that so hard to do.

const ProjectTitle = styled.h1 `
  margin:0;

  &:before {
    content: "1";
    font-size: 2rem;
    border: 1px solid black;
    padding: 0px 18px 6px 18px;
    border-radius: 50%;
    margin-top: 10px;
    margin-right: 10px;
    position: relative;
  }

`

enter image description here

CodePudding user response:

According to your code, the solution can be padding modification

h1 {
  margin: 0;
}

h1::before {
  content: "1";
  font-size: 2rem;
  border: 1px solid black;
  padding: 6px 18px; /* Aligned with 4 sides of the content*/
  border-radius: 50%;
  margin-top: 10px;
  margin-right: 10px;
  position: relative;
}
<h1>
  Testing
</h1>

CodePudding user response:

Mixing px and rem values to achieve alignment can be problematic as you don't know what the rem value will actually be.

This snippet instead uses flex to position the number centrally and makes the size of the circle dependant on rem value rather than padding with px.

h1 {
  ` margin: 0;
}

h1::before {
  content: "1";
  font-size: 2rem;
  width: 3rem;
  aspect-ratio: 1 / 1;
  border: 1px solid black;
  border-radius: 50%;
  margin-right: 10px;
  position: relative;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}
<h1>Testing</h1>

  • Related