skip to Main Content

On this page I used the strong::before{} pseudo element to add the star images you see before some of the chapter texts, such as here:

enter image description here

Unfortunately, as you can see, there is some odd offset to the star image, it sits above the text:

enter image description here

The code for that pseudo element is:

body .prime-steps .prime-section .section-content .min-height-section.chapter-formatting h3.c-accordion__title strong::before  {
    content: '';
    background: url(https://goodowners.dog/wp-content/uploads/2023/12/star_2_yellow_22px.png);
    display:inline-block;
    width: 22px;
    height: 22px;
    position: relative;
    margin-right: 10px;
}

Adding vertical-align:middle; for some reason creates the OPPOSITE problem, and the star sits below the text then – how odd!

Adding padding-top and margin-top to the image, that just pushes the whole thing down.

If you use the inspector, you can see that the h3 parent element has:

display:flex;
align-items: center;
align-text: center;

How can I get that pseudo element image middle-aligned vertically to the text?

I can work around it using transform:translatey(3px);, but that really doesn’t seem like the ‘proper’ way to do it.

2

Answers


  1. I would suggest adding this:

    strong {
      display: flex;
      align-items: center; /* optional */
    }
    

    You may prefer the result without align-items, depending on your preferred look.

    Login or Signup to reply.
  2. Best practices for using ::before and ::after for positioning involve ensuring that the parent is always set to a relative position, while these pseudo-elements should be set to an absolute position (don’t forget to use top, left, etc.).

    body .prime-steps .prime-section .section-content .min-height-section.chapter-formatting h3.c-accordion__title strong{
      position: relative;
      padding-left: 30px;
    }
    body .prime-steps .prime-section .section-content .min-height-section.chapter-formatting h3.c-accordion__title strong::before {
        content: '';
        background: url(https://goodowners.dog/wp-content/uploads/2023/12/star_2_yellow_22px.png);
        display: inline-block;
        width: 22px;
        height: 22px;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
    }
    

    In this way your pseudo element will always stays where ever you want without disturbing layout.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search