Centering text in a pseudo element vertically

I’ve been trying to find a way to centrally position vertically an ::after pseudo-element that includes text (a content attribute).

Previous inquiries: I reviewed some previous inquiries on this topic, however, none of the solutions seem to apply to this uncomplicated situation.

The scenario involves a straightforward DIV that functions as a "next" button. It features a simple right arrow (Unicode 0x203A).

The markup is quite basic:

<div class = "next-button"></div>

And here's the CSS used:

.next-button {
    position: absolute;
    height: 70px;
    line-height: 70px;
    text-align: center;
    background: black;
    cursor: pointer;
}

.next-button::after {
    content: "\203A";
    color: white;
    font-size: 3em;
    line-height: 0;

}

JSFiddle demo link: https://jsfiddle.net/me6a3nq2/

Hence, I attempted various techniques for achieving vertical alignment. To start with, vertical-align:middle doesn't have any impact in this instance. Another approach would be to set the parent element's line-height equivalent to its height, but this too proved ineffective.

I experimented with including position:relative in next-button::after and then adjusting the top accordingly. However, without knowing the precise height of the arrow and due to variations across browsers, the arrow wouldn’t be centered accurately.

Furthermore, I tried using a conventional CSS method involving translateY, as described here. Generally, I've had success with this technique:

.next-button::after {
    content: "\203A";
    color: white;
    font-size: 3em;
    line-height: 0;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Even so, this approach didn't work seamlessly with the pseudo-element. In Chrome, it appeared to shift the arrow off-centered towards the bottom:

https://i.sstatic.net/XyFX4.png

Furthermore, scrutinizing through the Chrome Inspector tool, I observed that the arrow itself (essentially a text character) appeared to have automatic padding above and below. This automatically added “padding” seemed larger above than below, thereby throwing off the vertical alignment of the arrow:

https://i.sstatic.net/ouagr.png

...however, I couldn't discern the cause of this padding or how to manipulate it. Initially, I presumed it might be related to line-height, hence I set line-height to 0, unfortunately to no avail.

So, my ideas are exhausted. I'm contemplating abandoning the usage of a pseudo-element and resorting to placing the arrow within a nested DIV instead.

Issue: Is there any viable means to vertically align a pseudo-element? (Additionally, what could be causing the unexpected padding above and below the text within the pseudo-element’s content?)

Answer №1

If you're okay with it, go ahead and set line-height: 65px;:

That's the approach I take in my own projects. However, if the height changes, you'll need to adjust the line-height accordingly. The issue here is that these symbols are not vertically centered at their visual center, but on the text baseline. As far as I'm aware, there isn't a perfect solution for this.

.next-button {
  position: absolute;
  height: 70px;
  line-height: 70px;
  text-align: center;
  background: black;
  cursor: pointer;
}
.next-button::after {
  font-family: Arial;
  content: "\203A";
  color: white;
  font-size: 3em;
  line-height: 65px;
}
<div class="next-button"></div>

Answer №2

Is it possible to align a pseudo element vertically?

Absolutely, and all the methods you mentioned are effective.

For instance, using the transform technique - simply apply a border to the character - and observe how the character is centered within the red border area (Check out this Fiddle Demo)

The issue lies in the fact that the actual character glyph itself isn't centered - which may be intentional, similar to how an underscore character is not centered either.

Hence, this discrepancy is not related to pseudo elements but rather the specific character being centered.

You will need to either adjust manually to center the character or opt for a different arrow symbol instead.

Answer №3

Even though utilizing line-height could work, I stumbled upon an alternative solution!

All you have to do is apply vertical-align:sub to the pseudo element of .next-button.

Feel free to check out the fiddle below.

    .next-button {
    position: absolute;
    height: 70px;
    line-height: 70px;
    text-align: center;
    background: black;
    cursor: pointer;
    }
    
    .next-button::after {
    content: "\203A";
    color: white;
    font-size: 3em;
    line-height: 0;
      vertical-align: sub;
   }
<body>
<div class = "next-button"></div>
</body>

Answer №4

Utilizing flexbox in CSS3 is a great way to create flexible layouts.

display: flex,
justify-content: center  // you can also experiment with space-around or other options.

// alternative methods:
align-item: center  or;
align-self: center

Check out this example for more information: How to use Flexbox in CSS

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Deeply Nested Routing in Angular

I've been exploring the use of multiple router outlets and encountered an issue. When using the navigateBy function of the router, I am unable to view my child route and encounter an error. However, when I access it via the routerLink in HTML, I get ...

Using the innerHTML property to place an Img tag within a div element

I'm facing an issue with including multiple tags within a div using innerHTML. To better illustrate my problem, here's an example: var y = "jack.jpg"; var x = "Jack"; var f = "Hello world!"; document.getElementById("maindDiv").innerHTML += "< ...

How can CSS grid be utilized to create columns of various widths that wrap onto a new line

Struggling with CSS grid in my new responsive design, particularly regarding wrapping. The issue is with a nav bar containing a header that needs to be aligned left and four buttons that should be aligned right. Currently, using: grid-template-columns: r ...

Attempting to achieve the simultaneous display of an image overlay and image zoom when hovering over the mouse

I'm struggling to display an image overlay and image zoom simultaneously when hovering the mouse. After adding the image zoom effect, the overlay disappears. It seems like one transition is overriding the other. Whenever the zoom works, the overlay do ...

Using CSS files in the web directory in CakePHP and connecting them to HTML

Could someone offer some help with cakephp? I'm experiencing an issue related to routes that I can't seem to resolve. I've organized all my css files in webroot/css within my app. In my default layout, I included a html link <link href=" ...

Arrange a group of users in the middle

Looking for some help with this specific code snippet .selection_user { display: block; background-color: #2D2C31; text-align: center; line-height: 75px; } <div class="select_user_menu"> <div class="selection_user">User1</div> ...

What is the best method for obtaining a modified image (img) source (src) on the server side?

Having some trouble with a concept in ASP.Net that's causing me quite the headache. I am fairly new to ASP.Net and struggling with something that seems much easier in PHP. I created an img element with an empty src attribute : <img runat="server" ...

Can the height of an input element be set to zero?

Currently, I am utilizing CSS transitions to adjust the height of an input element from 40px to 0px in an attempt to make it disappear. While this technique works effectively for images and yields a satisfactory result, it seems to fall short when applied ...

Struggling with aligning content within a div using CSS grid techniques

I am experimenting with CSS Grid and running into issues with overlaying content. The structure consists of a top-level container defined as a CSS grid (class="container"), followed by a content grid (class="content") that divides into 3 rows (header, labe ...

I am currently working with CakePHP and am interested in learning how to expire the admin session

I'm having issues with the code in my UserController. When I open the admin panel in two tabs within the same browser and log out from one tab, I am unable to redirect to the login page from the other tab when clicking on any menu. function beforeFil ...

CSS navigation bar (background gradient problem)

I have encountered an issue with my multi-tier navigation menu where tiers below tier 1 are displaying an unexpected block to the left of the options. I suspect this problem is related to the background gradient applied, but I haven't been able to fin ...

Tips for effectively deleting a flash object from an HTML page

I recently created a website with AJAX (using jquery) for navigation purposes. The pages on the site slide smoothly, and I have been using remove() to get rid of the old page. Everything was working fine until I encountered an issue where the browser cras ...

JavaScript code for iframe auto resizing is not functioning properly on Firefox browser

I have implemented a script to automatically resize the height and width of an iframe based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newh ...

Dealing with Overflow in CSS DIV Elements

Link to site: Suddenly, without any changes to the css, I noticed that when I expand the "browse" categories, they overflow outside of the containing divs. Here is the css code for the divs: .bodyArea { width: 900px; background-image:url(/images/ ...

Element mysteriously concealed in certain Safari cases, consistently visible in Firefox and Chrome

A new angular application has been developed as a "bounce" page for an upcoming social iOS app currently in public beta. Users have the ability to share their profiles by simply providing a link to the site. If the page is accessed via an iOS device w ...

A single image with dual clickable areas managed by an interactive image map

Is there a way to attach two href links to one image using CSS? I want it to function like an old school image map, but purely with CSS. Is this something that can be done? The current HTML code looks like the example below. However, I need the image to h ...

What is the best way to animate images moving from the center to the left in HTML?

I've been pondering how to create a unique effect where images smoothly move from the center to the left, similar to what is showcased on this website: My attempts using the <marquee> tag have only resulted in images scrolling from right to lef ...

Can you show me the steps for downloading the WebPage component?

My goal is to save webpages offline for future use, but when I download them as html many of the included components disappear! I attempted opening them in a WebBrowser and downloading as html with no success. One potential solution is to download the ht ...

Retrieve a HTML element's tag using jQuery

I have a search bar with two tabs to choose from for the type of search. I am looking to assign the .active class to the list item whose search_type matches a parameter from a request (e.g., params[request_type]). <ul data-tabs="tabs" class="tabs"> ...

Is there a way to automatically retrieve CSV data using ashx on a web page?

After researching the provided links from SO without success, I decided to reach out here for help. (For privacy reasons, the actual URL and header data have been obscured) I am struggling to automate downloading data from an HTTPS web page using Delphi ...