Consider the code snippet below:
<div class="example-container">
<p class="example">a</p>
<p class="example">bbb</p>
<p class="example">cc</p>
</div>
and the corresponding css:
.example-container {
display: grid;
/* adapted grid-template-column for mobile view */
grid-template-column: repeat(1, 1fr);
justify-items: center;
}
.example-container .example {
/* some styles */
}
.example-container .example::before {
content: "symbol";
/* some style for content */
display: inline-block;
width: 1.5rem;
margin-left: -1rem;
}
Although justify-content
centers the child element, it does not align the ::before
pseudo element properly. To achieve this, I tried the following css rules:
.example-container {
width: max-content;
margin: auto;
}
.example-container .example {
min-width: 100%;
}
This only centers the child element without its pseudo element (similar to how margin: auto
works). Even making the parent of .example-container
a flex
container did not align both elements in the center.
I believe achieving this alignment can be done using CSS tricks only, as some users may have JavaScript disabled or restricted on certain websites. One possible solution could involve calculating the widths of the pseudo element and child element with JavaScript, but I prefer a pure CSS approach.
-----Update----- Here is a visual representation of the desired layout:
+--------------------------+
| O a |
| O bbb |
| O cc |
+--------------------------+
# I use O to mimic a symbol.