Home > Software engineering >  How to properly centre CSS pseudo elements in their base element
How to properly centre CSS pseudo elements in their base element

Time:09-17

I created a circle in CSS and I created another circle using pseudo-elements 'after'. but the created pseudo-element circle is not properly centred in the main circle.

can someone tell me what are the different ways to centre pseudo elements?

Thanks.

.main{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.first{
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: rgb(202, 202, 202);
    cursor: pointer;
    box-shadow: 0 0 6px 1px #e8eef6;
    position: relative;
}

.first::after{
    content: '';
    height: 70px;
    width: 70px;
    border-radius: 50%;
    background-color: rgb(78, 78, 78);
    position: absolute;
}
<div >
        <div ></div>
         </div>

CodePudding user response:

You'll have to use the transform property and translate method and you'll also need top and left properly.

with top: 50%; we'll set top position to 50% and with left: 50%; we'll set left position to 50%

then with transform: translate(-50%, -50%); we'll change horizontal and vertical directions.

so the below combination is generally used to center alignement with position absolute.

 top: 50%;
left: 50%;
transform: translate(-50%, -50%);

.main {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.first {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: rgb(202, 202, 202);
  cursor: pointer;
  box-shadow: 0 0 6px 1px #e8eef6;
  position: relative;
}

.first::after {
  content: '';
  height: 70px;
  width: 70px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  background-color: rgb(78, 78, 78);
  position: absolute;
}
<div >
  <div ></div>
</div>

CodePudding user response:

You're already using flex, so stick with it:

.first {
  display: flex;
  place-content: center;
  place-items: center;
}

.main {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.first {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: rgb(202, 202, 202);
  cursor: pointer;
  box-shadow: 0 0 6px 1px #e8eef6;
  position: relative;
  display: flex;
  place-content: center;
  place-items: center;
}

.first::after {
  content: '';
  height: 70px;
  width: 70px;
  border-radius: 50%;
  background-color: rgb(78, 78, 78);
}
<div >
  <div ></div>
</div>

  • Related