What is the best way to align a character at the center of a box with CSS?

Essentially, how can I vertically center a character within a box based solely on its bounding box dimensions, disregarding its depth and ascent?

Here is a simple HTML example:

.box {
  display: inline-block;
  width: 1em;
  height: 1em;
  line-height: 1em;
  border: 1px solid black;
  text-align: center;
}
<span class="box">?</span>
<span class="box">,</span>
<span class="box">`</span>

This code snippet generates the following output:

https://i.sstatic.net/5ZqAS.png

Is there a way to modify it in order to achieve this output instead?

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

If possible, CSS solutions are preferred over Javascript. However, JavaScript is acceptable as a last resort. The objective is to find a solution that works universally, not just for the depicted characters. Given that there will be multiple boxes on my webpage, performance (especially if using JavaScript) is crucial.

To provide further clarification, here's how I would tackle this problem in LaTeX:

\newlength{\desiredboxsize}
\setlength{\desiredboxsize}{1em}
\newcommand*{\centercharinbox}[1]{%
  % Force width
  \makebox[\desiredboxsize]{%
    % Force height and vertically center
    \raisebox{\dimexpr .5\desiredboxsize - .5\height \relax}[\desiredboxsize][0pt]{%
      % Cancel depth
      \raisebox{\depth}{#1}}}}

Answer №1

Theoretically, aligning each symbol individually is possible.

In reality, it's not feasible because each symbol has its unique depth and ascent in the character map, especially when relying solely on CSS for alignment.

Answer №2

To achieve this effect using modern CSS is not possible. Similarly, achieving it using JavaScript in browsers straight out of the box is also not feasible.

The solution lies in obtaining glyph outlines as paths from fonts. By utilizing this data, one can accurately determine the path outline box and customize its rendering or alignment as needed.

If you're interested in acquiring glyph outlines, refer to this How do I get glyph outlines of a letter as bézier paths using JavaScript? helpful answer.

Once you have access to glyph outline paths, you can easily render them within <canvas> elements.

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

Retrieve CSS height using Jquery, based on the declared value rather than the computed value

In a previous version of jQuery, the default behavior was different. When I use .css("height") and .height(), it gives me the computed height instead of what I actually want. I only need the height value if it is explicitly declared in the CSS for that ele ...

Passing references between multiple components

I'm currently working on an application using Material-UI in conjunction with styled-components. I am faced with the challenge of passing a ref down to the root <button> node that is created by Material-UI. Material-UI provides a buttonRef prop ...

Looking for help with aligning an icon to the right side of my text

I'm struggling with aligning the icon to the right of the quantity. When I use float:right, it places the icon at the far right of the cell instead of next to the text. Is there a way to get it to be on the right side of the text but directly adjacent ...

Can the background image of a div be cropped using CSS/JavaScript techniques?

I have a div with a background image of a world map that I need to clip at two precise points. Clipping from the left side is straightforward. In my CSS: .le-map { background-image: url('../img/le-map-of-le-world.mlg'); background-size: 100% ...

Issues with Angular-Trix compatibility with Internet Explorer 10

I am currently using the Angular-trix rich text editor, which is functioning perfectly in all browsers including IE 11. However, I am encountering issues with it not working in IE10 or earlier versions. An error message that keeps appearing states: Una ...

I am puzzled as to why my text and div boxes are displaying in my navbar/hamburger menu instead of at the bottom of the page

Greetings, everyone! This is my debut post here so bear with me if it's not presented in the correct format. Currently, I am deep into creating a website using HTML, CSS, and just a hint of JavaScript. My primary focus right now is on building the ho ...

Conflicting styles between Bootstrap and Formstack are causing radio buttons to appear only partially visible

Encountering a conflict between Bootstrap (4.1.3) and Formstack CSS when trying to embed a form in a website. The radio buttons are not fully visible, with the issue located in the "label" class ("fsOptionLabel"). Adjusting the line height provides a parti ...

Custom Angular directive for collapsing sub menus with CSS

I found a helpful article on creating collapsible menus and submenus using only Bootstrap and custom code for Angular 2, 4, 5, 6. I've been able to implement the logic successfully, but I'm facing an issue with multiple menus where clicking on an ...

Enabling scrolling for a designated section of the website

Example Link to Plunker <clr-main-container> <div class="content-container"> <div class="content-area"> <div class="row"> <div class="col-xs-9" style="height:100%; border-right: 1px solid rgb(204, 204, 204); padding-ri ...

The excessive height of a Bootstrap 5 row is causing the image to overflow beyond the container

I am currently working on setting a maximum height for a banner I am designing in bootstrap5. Here is my code snippet: .banner { background: red; max-height: 50px; } <head> <title>Example</title> <meta charset="utf-8" ...

Hovering over a white background will darken the CSS styling

A stunning image on a dark background Displayed on Hover (right) An elegant picture with a white background Activated on hover (incorrectly) I would like it to have a darkened effect on the white background as well. CSS Styling .photo background: n ...

Tips for creating a mobile-friendly appointment section on your website

Hey guys, I need some help with a problem I'm having. I created an appointment page that works perfectly on desktop mode, but when I try to view it on mobile, it's not responsive. Can anyone assist me in fixing this issue? Appointment.js Here ...

Setting size using percentages in Semantic-UILet's explore how to define the size

Since discovering semantic-ui a few days ago, I've been impressed and have decided to switch my app from Bootstrap 3 to semantic-ui. I could use some assistance here. I'm attempting to split the body of the page into two parts. I would like the ...

Prestashop 1.7 - Enhanced top menu navigation with drop-down subcategories

While using the ps_mainmenu top menu with the default Prestashop theme, I noticed that the drop-down menu only works for parent categories and not subcategories. You can see this in the attached image and HTML code from Chrome. I'm looking for a way t ...

Employ a distinct styling approach for Chrome and Mozilla with only utilizing a single style

This is the CSS style defined in a PHP file for an Element line-height: 120px; display: list-item; display: -moz-inline; list-style: none; If the browser is Chrome, I want it to show display: list-item, and if it's Mozilla, then display: inline. Th ...

HTML/CSS - Troubleshooting Animation Issues

I am currently experimenting with different website animations and implementing responsive design. However, I encountered an issue when trying to apply these changes to my header, which also affects the .heading element. It seems that there is a problem w ...

Display a <button> element as a text hyperlink within a paragraph, ensuring proper wrapping and flow

I want to incorporate a link-styled <button> within a block of text while ensuring that it flows smoothly with the surrounding content. Although styling the button is straightforward and setting display: inline allows it to blend into the text flow, ...

Bootstrap - Struggling to achieve responsiveness on the page

I've recently designed a website with a mega menu feature. However, as I try to resize the page, the layout doesn't adjust well, and some elements appear to be overflowing beyond the screen. Unfortunately, I can't share the entire code. Cou ...

When you add CSS font-size to the body element, how can you effectively manage the nesting of tags and the concept of inheritance within

Currently revamping a website loaded with old content. The main change in design is to make the site adaptable to different screen sizes. I am utilizing the font-size in the body element for this purpose and setting all measurements to ems. While this meth ...

Ways to verify an iCheck located on the following page

Here is the code snippet I am currently working with: $("#add-new-size-grp").click( function (event) { event.preventDefault(); $.ajax({ type: "get", url:"ajax-get-sizes.php", success: function(result){ $("#sizeg ...