Let's say we have the following example code:
<div >
<p >a</p>
<p >bbb</p>
<p >cc</p>
</div>
and the css:
.sample-container {
display: grid;
/* adapted grid-template-column for mobile view */
grid-template-column: repeat(1, 1fr);
justify-items: center;
}
.sample-container .sample {
/* some styles */
}
.sample-container .sample::before {
content: "symbol";
/* some style for content */
display: inline-block;
width: 1.5rem;
margin-left: -1rem;
}
While justify-content
does center the child at this point, the ::before
pseudo element wouldn't be aligned. However, if I do:
.sample-container {
width: max-content;
margin: auto;
}
.sample-container .sample {
min-width: 100%;
}
It would only align the child without it's pseudo element to the center (as how margin: auto
works). I also tried to make the parent of .sample-container
flex
and it still centers only the element itself without considering the pseudo elements.
I think it can be achieved with JS by getting the width of pseudo element and the child, then place them in the center, but I want it could be achieved with css tricks only (some people for whatever reason doesn't enable js, or whitelist only certain website to use js).
-----Update----- To make it clear, here is a simple visual presentation:
--------------------------
| O a |
| O bbb |
| O cc |
--------------------------
# I use O to mimic a symbol.
CodePudding user response:
Just delete width: 1.5rem;
and margin-left: -1rem;
from .sample-container .sample::before
. Use display:inline-flex
and position it with position:relative; left:50%; transform: translateX(-50%);
.sample-container {
display: inline-flex;
flex-direction: column;
justify-content: center;
position: relative;
left: 50%;
transform: translateX(-50%);
}
.sample-container .sample {
/* some styles */
}
.sample-container .sample::before {
content: "symbol";
/* some style for content */
display: inline-block;
margin-right: 1rem;
}
<div >
<p >a</p>
<p >bbb</p>
<p >cc</p>
</div>
CodePudding user response:
This seems aligned and centered to me. And maybe just wrap everything inside a span or div that will be centered?
.sample-container {
display: grid;
/* adapted grid-template-column for mobile view */
grid-template-column: repeat(1, 1fr);
justify-items: center;
}
.sample-container .sample {
/* some styles */
}
.sample-container .sample::before {
content: "symbol";
/* some style for content */
display: inline-block;
margin-left: -1rem;
color: red;
}
.all {
display:inline-block;
border: 1px solid blue;
}
<div >
<div >
<p >a</p>
<p >bbb</p>
<p >cc</p>
</div>
</div>