There is a slight misalignment when trying to horizontally center a character within a div

I've experimented with various methods like using a px width or em widths. I've attempted nesting a span and trying different styles such as text-align:center or margin:0 auto.

I can manage to center either the R or the S, but struggling to get both of them centered using the same style. It's crucial for them to be centered in the same manner since the character is not fixed in this example.

Adjusting the font size sometimes shifts which item is centered. Zooming my browser to 300% makes them both appear centered, but that is not a practical solution. :)

<style>
div { margin-bottom:10px; }

span {
  display:inline-block;
  width:16px;
  border:1px solid #000;
  text-align:center;
  margin-left:20px;
}

.example2 span {
  border-radius:50%;
}
</style>
<div class="example1">
<span>R</span> <span>S</span>
</div>

<div class="example2">
<span>R</span> <span>S</span>
</div>

http://codepen.io/anon/pen/NrqJLX

https://i.stack.imgur.com/ZlnA7.png

The 'S' seems to be slightly off to the right by 1 pixel.

Although I've come across many similar stackoverflow questions, none quite match my specific issue. Apologies if this has been previously addressed.

Answer №1

Aside from the size of the glyphs, a dilemma arises in this scenario where the space between the rectangle and the circle is 16px and 14px respectively, and the width of the "S" visually appears as 7px. This leaves no room for it to be positioned at a half pixel's position, requiring it to be either 1px to the right or left.

This issue persists regardless of whether you use a monospaced font or not. Some letters' visual width (or height) minus the available space divided by 2 may not always result in an even distribution of space on both sides, potentially causing the letter to appear 1 pixel off center to the left or right (top or bottom).

In my opinion, utilizing flexbox would effectively centralize the elements. I suggest replacing display: inline-block with the following code snippet:

display: inline-flex;      /* used inline-flex to keep the span side-by-side */
justify-content: center;   /* horizontal alignment when using row direction */
align-items: center;       /* vertical alignment                 -  "  -           */

Here is a sample snippet demonstrating the implementation:

div {
  margin-bottom:10px; 
}

span {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width:16px;
  border:1px solid #000;
  margin-left:20px;
}

.example2 span {
  border-radius:50%;
}
<div class="example1">
<span>R</span> <span>S</span>
</div>

<div class="example2">
<span>R</span> <span>S</span>
</div>

Answer №2

The answer is quite simple - the center of a character may not be where you expect it to be. Character glyphs vary in width, especially in "normal" fonts and typefaces.

In non-monospace or sans-serif fonts, factors like ascenders, descenders, and serifs can impact the dimensions of the character glyphs.

To achieve greater accuracy, consider setting the width/height/line-height in em. If absolute pixel precision is crucial to you, manual adjustments might be necessary.

div {
  margin-bottom: 10px;
  display: inline-block;
  vertical-align: top;
}
span {
  display: inline-block;
  width: 1em;
  height: 1em;
  font-size: 144px;
  line-height: 1em;
  border: 1px solid #000;
  text-align: center;
  margin-left: 20px;
}
.example2 span {
  border-radius: 50%;
}
.other {
  font-family: monospace
}
<div class="example2">
  <span>R</span>  <span>S</span>
</div>

<div class="example2 other">
  <span>R</span>  <span>S</span>
</div>

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

Troubles with Placing Image on WordPress

Working on a Wordpress component for a website where I placed a "SOLD OUT" image over text. However, the issue arises when viewing the site on mobile devices, as the images are smaller and not in their correct positions due to using absolute positioning. ...

What is the best way to divide the height of one div evenly among three other divs?

I have three child divs inside a parent div and I'm looking to distribute the height of the parent div evenly among the three children. Here is the HTML code: <div class="frameright"> <div class="divright"> <t ...

For a while now, I've been attempting to transform my paragraph into a block within a section that showcases elements in an inline-flex layout

I have been attempting to adjust the paragraph with the errorDate class so that it displays as a block element directly beneath the input element similar to the image provided here. The section is currently set to appear as an inline-flex. Below is the CS ...

Difficulty in vertical alignment of inline-block elements

Greetings, I am currently working on creating a Resume in HTML. However, I seem to be facing an issue with the inline-block property as the two div elements that should be placed next to each other are not displaying as expected - one of them appears sligh ...

Troubleshooting a Cache Issue in Your Next.js Application

Whenever I attempt to run 'npm run build', an error crops up that seems to be linked to the css and fonts. Unfortunately, I am unsure of how to tackle this problem. It's perplexing as the app functions perfectly fine in development mode. Th ...

The layout in Next.js production builds appears to be distinct from the layout in the

Currently, I am working on a website where I have implemented a dark theme by adding a class to the body element. Everything is functioning perfectly in the development environment, but I am encountering issues in the production build. Here is the root l ...

Issue with drop-down menu functionality on mobile-friendly website

After deciding to revamp my website for responsiveness, I encountered an issue with the menu not displaying on smaller screens. Everything else is functioning correctly except for the drop-down menu! Here is the HTML code: <!doctype html> <html ...

Creating a horizontal alignment for social media icons

Need assistance with aligning my social icons horizontally. I initially tried floating them to the left or using inline-block, but it's not working as expected. Any help would be greatly appreciated. Thanks! <!-- Customizing Social Network Icons ...

Mobile Image Gallery by Adobe Edge

My current project involves using Adobe Edge Animate for the majority of my website, but I am looking to create a mobile version as well. In order to achieve this, I need to transition from onClick events to onTouch events. However, I am struggling to find ...

CSS - using numbers to create dynamic background images

I am looking to create a design where the background images in CSS display increasing numbers per article, like this example: This idea is similar to another post on Stack Overflow discussing using text as background images for CSS. You can find it here: ...

Exploring jQuery Efficiency: Comparing CSS and Animation Techniques

I am trying to steer clear of using the animation property because it tends to be slower compared to CSS3 animations. My query is whether utilizing the css method is faster than the animation property, but still slower than a direct CSS3 animation with tr ...

Exploring the power of CSS grid in React/Gatsby for creating dynamic layouts with varying numbers of columns in each

I need help creating a dynamic grid layout where the number of columns alternates between rows. For example, I want the first row to have one column, the second row to have two columns, and so on. Right now, my grid only has two columns per row. Does anyon ...

Creating a circular shape with a radius that can be adjusted

I'm trying to create an expanding bubble-like circle of various colors when clicked on a blank page. The circle should continue increasing in size each time it is clicked, only stopping when the mouse click is released. I am looking to use HTML, CSS, ...

I encountered a SyntaxError indicating a missing ")" right before utilizing jQuery in my code

When trying to run the code below, I encountered an error in the console stating SyntaxError: missing ) after argument list. $(document).ready(function() { $(".blog-sidebar-form form").before("<p class="blog-sidebar-inform>Dummy Text</ ...

What strategies and techniques should be considered when creating websites optimized for mobile devices?

With a wealth of experience in programming languages like Java, Python, and C, I actively engage in self-study to enhance my skills. While I have dabbled in creating mobile-friendly websites, upon reviewing my work, it is evident that my frontend developme ...

jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/ Let me explain the functionality of the code The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second contai ...

Error occurred during the file watch process in PhpStorm after saving the CSSO file

Following the advice in the official PhpStorm documentation, I have implemented a CSS minifier. However, upon attempting to use it, I encountered the following error: cmd.exe /D /C call C:\Users\douglas\AppData\Roaming\npm\css ...

What is the best way to center my form vertically within the form container?

I am having trouble aligning my form vertically. I've experimented with different methods such as using display: table-cell and vertical-align: middle property, but nothing seems to work. I want to maintain the current structure of the page and would ...

MUI enables the creation of a fixed vertical box anchored at the bottom of the screen

I’ve attempted the following so far: import "./styles.css"; import { Box, Typography } from "@mui/material"; import styled from "@emotion/styled"; export default function App() { const MainStyle = styled("div")(( ...

Issue with Flex display not being applied within Material UI Grid Item

I am attempting to position an element at the end of a Grid Item (horizontally). In order to achieve this, I am enclosing my component in the following div: Here is the complete code snippet: <Grid container spacing={8} alignItems={'stretch' ...