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

"Unexpected behavior: datatables.net plugin causing left menu to be hidden behind table in Internet

My webpage was functioning perfectly in Internet Explorer. I decided to enhance it by incorporating the impressive jQuery plugin Datatables. I added the following code in DOMReady: $('#articlestable-container table').dataTable({ "bPaginate ...

Creating a carousel with a curved dial or wheel: A step-by-step guide

My goal is to create a carousel with curved container and downward movement for items not in focus. The description should change based on the focused item, and I prefer the carousel not to autoplay. via GIPHY I've been searching online for a soluti ...

How to Vertically Center a Span in a Mat-Header-Cell with Angular 5 Material

In my angular5 application, I am utilizing a material table to showcase some data. Within a mat-header-cell, I have a combination of a span and an img, and I'm attempting to align them correctly. This is how it currently appears: Below is the snipp ...

Unable to initialize styles in a newly created Angular CLI project

Just finished setting up a new project with the angular cli. Encountering an issue when trying to link the styles.css file in index.html <link rel="stylesheet" type="text/css" href="styles.css"> Getting the following error in Chrome's dev too ...

The printed Bootstrap web page is being truncated

I have a unique dynamic webpage created with Bootstrap that needs to be printable. I am implementing media queries for styling the page when printing: /** Custom Print Styles **/ @media print { header, .menu, footer { display: none; ...

What causes the content of a sticky navbar to overflow?

I have a situation where my navbar has two styles (.navbar and .navbar_fixed), but the links in the navbar are not fitting properly. I attempted to remove padding and add left: 0;, however, these adjustments did not work as expected. Any suggestions on how ...

When I hover over the navigation bar, a submenu pops up. However, as I try to navigate to the submenu, I often end up accidentally selecting a different item on the navigation bar

I'm trying to find an answer but can't seem to remember where I saw it. Here's the situation: a horizontal nav bar with a dark blue selection and a red sub-menu. When the user hovers over a black arrow, it crosses into a light-blue nav item ...

Tips for customizing the appearance of popup windows

I want to enhance the appearance of my popup window by applying a different format for opening it. How can I style it so that it looks visually appealing when the popup window opens? You can find below the source code I am working with: HTML: <div onM ...

Implementing Materialize CSS functionality for deleting chips

I've been attempting to extract the tag of a deleted chip from the div within the Materialize chips class, but I'm hitting roadblocks. My failed attempts so far: $('.chips').on('chip.delete', function(e, chip){ console.lo ...

Creating an unordered list (ul) with list items (li) that extend the full width

Having trouble making my list items (li) from the unordered list (ul) stretch across the page like the navigation bars on websites such as Verragio and James Allen. Can someone assist me with this? Here is a basic example of a nav hover bar. .dropdown-b ...

What is the best way to horizontally align and center the navigation menu?

I've been struggling to center and align the navigation links inside this div horizontally. I attempted a few methods, but none seem to work. I managed to fix the previous issue with #centermenu, but unfortunately it still isn't functioning as e ...

CSS overflowing issue causing inability to reach bottom of div with scroll bars not functioning as anticipated

My objective is to create a layout featuring a sticky header and left sidebar, with a non-sticky DashboardBody (the green-bordered box) that can be scrolled through. When scrolling, I want the content at the top to disappear "under" the sticky header. The ...

I require varying numbers of columns on each row based on the breakpoint in Bootstrap4

After realizing it was easier than expected, I simply consolidated all columns into one row and the responsiveness now works perfectly. Thank you to everyone who helped. I am utilizing Bootstrap 4 grid system to structure 3 rows with columns. For lg brea ...

Mobile-responsive iFrame content is designed to adjust and fit appropriately on

While my iframe is responsive on both mobile and website, I am facing an issue where the content overflows (both overflow X and Y) from the width and height of the iFrame. Here's the scenario: in the mobile view (simulated using Google Chrome to mimi ...

Tips for seamlessly integrating full-size images into the slider?

I'm a beginner when it comes to CSS and I am having trouble fitting two images inside my first slider. My goal is to display the full images within the slider, but the width of the images exceeds that of the slider. Below is the CSS code for the slid ...

Save this text in HTML format to the clipboard without including any styling

When using this code to copy a htmlLink to the clipboard: htmlLink = "<a href='#'>link</a>"; var copyDiv = document.createElement('div'); copyDiv.contentEditable = true; document.body.appendChild(copyDiv); ...

Ensure that the div elements fully occupy the remaining space within the box

I'm looking to bring this idea to life: https://i.sstatic.net/SWytj.png Most of my work is complete, but I need the boxes to fill up all available space in the row. This is the HTML code I've used with Bootstrap. How can I achieve this? < ...

CSS files are failing to load in ASP .NET framework

I am facing a similar issue to the one described by another user on Stack Overflow here: Asp.NET not applying my CSS files However, after adding the following code to my web.config file, nothing seems to change: <location path="css"> &l ...

Increase visibility, decrease visibility by utilizing ng-hide/ng-show and functions

As I implement the show more/show less feature, I am uncertain if achieving a smooth effect is feasible. However, I believe it's worth reaching out to this community for some creative ideas on how to make it possible. I have a list of dynamic links w ...

Safari's problem with CSS transitions

This issue is specific to Safari, as it has been tested and works fine in Chrome, Opera, and Firefox. Upon hovering over a certain div (1), a child div (2) slides out by adjusting the left property. However, the child elements (buttons) within the second ...