Reputation: 1085
I am currently working on a project in which I am using some divs, and the :after
pseudo-element. I would like to be able to center the :after
text inside the div. Can anybody help me out here?
Example of problem: http://jsfiddle.net/JohnFish/7ra5t/
Upvotes: 1
Views: 11509
Reputation: 2399
The following will center the overlay on a media element. The CSS includes some extra properties to demonstrate related issues when trying to center overlays.
Notes:
video
and image
do not support :before
or :after
directly. They need a wrapper.
display: block
to avoid unexpected inline related line-height issues when trying to center other elements on top.:after
shows up on top of the wrapped element, and can display backgrounds on the overlay.inset
is shorthand for top right bottom left
.inset
set to auto
for the trailing bits prevents stretching backgrounds.translate
shifts the entire element, including the trailing bits.content
accepts attr()
references to element properties to grab the text content. This pairs well with programmatic setting of data
properties in the HTML code..pics {
display: flex;
gap: .5em;
flex-wrap: wrap;
}
.wrapper {
position: relative;
width: fit-content;
height: fit-content;
/* can ignore items below this line */
border-radius: .5em;
overflow: hidden;
}
img {
display: block;
}
.wrapper:after {
position: absolute;
inset: 50% auto auto 50%;
transform: translate(-50%, -50%);
content: attr(data-overlay);
/* can ignore items below this line */
background-color: white;
padding: .5em 1em;
opacity: .8;
border-radius: .5em;
box-shadow: 1px 1px 3px 0 black;
}
<div class="pics">
<div class="wrapper" data-overlay="Overlay 1">
<img src="https://picsum.photos/200" alt="Pic 1" />
</div>
<div class="wrapper" data-overlay="Overlay 2">
<img src="https://picsum.photos/300/200" alt="Pic 2" />
</div>
<div class="wrapper" data-overlay="Overlay 3">
<img src="https://picsum.photos/200/300" alt="Pic 3" />
</div>
</div>
Upvotes: 0
Reputation: 2302
You can also try with flex
.example {
display: flex;
justify-content: center;
}
Upvotes: 1
Reputation: 106365
Another way to do it:
.example { ... position: relative; }
.example:after { ...
position: absolute;
top: 50%; margin-top: -{50% of the element's height};
left: 50%; margin-left: -{50% of the element's width};
}
Upvotes: 4
Reputation: 1723
I think you just have to add a text-align: center
in your CSS:
.example {
background: black;
height: 250px;
width: 500px;
text-align: center
}
.example:after {
content: "+";
color: white;
font-size: 100px;
}
If you also want vertical alignment:
.example {
background: black;
height: 250px;
width: 500px;
text-align: center;
display: table-cell;
vertical-align: middle;
}
.example:after {
content: "+";
color: white;
font-size: 100px;
}
Upvotes: 4