What is the best way to center an HTML element between two other elements?

Kindly, take a look at this straightforward jsFiddle: http://jsfiddle.net/mark69_fnd/vtLrt/10/

HTML:

<div class="char">
  <div>
    <div class="char">A1</div>
    <div class="char anchorToMiddle">D1</div>
    <div class="char anchorToRight">G1</div>
  </div>
  <div>
    <div class="char">A2</div>
    <div class="char anchorToMiddle">D2</div>
    <div class="char anchorToRight">G2</div>
  </div>
  <div>
    <div class="char">A3</div>
    <div class="char">B3</div>
    <div class="char">C3</div>
    <div class="char">D3</div>
    <div class="char">E3</div>
    <div class="char">F3</div>
    <div class="char">G3</div>
  </div>
</div>​

CSS:

.char{
    display: inline-block;
}


.anchorToRight {
    float: right;
}​

Output:

In what ways can I modify the HTML and/or CSS to have the items labeled as anchorToMiddle (D1 and D2) centered in the middle directly above D3?

Thank you.

Answer №1

In an attempt to solve the issue, I turned to some javascript code (given that the question had a javascript tag).

By applying "text-align: center" to the "anchorToMiddle" class, the text can be centered, but only if you specify the width of the element. To achieve this, B3..F3 elements are enclosed within another div (with the id "charspan"):

<div id="charspan" class="char">
    <div class="char">B3</div>
    <!-- etc. -->
</div>

Subsequently, the width of this new div is calculated and then applied to the "anchorToMiddle" class.

var elems, i, width, span;
elems = document.getElementsByClassName("anchorToMiddle");
span = document.getElementById("charspan");
width = parseInt(window.getComputedStyle(span).width);
for (i = 0; i < elems.length; i++) {
        elems[i].style.width = width + 'px';
}

View the updated Fiddle here: http://jsfiddle.net/Espesen/vtLrt/14/

Answer №2

To resolve the issue, adjust the width and apply the text-align:center; property.

I have made changes to your FIDDLE

Answer №3

Have you considered using a 3x7 table instead?

<table>

    <tr>

        <td>X1</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>Y1</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>Z1</td>

    </tr>

    <tr>

        <td>X2</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>Y2</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>Z2</td>

    </tr>

    <tr>

        <td>X3</td>
        <td>P3</td>
        <td>Q3</td>
        <td>R3</td>
        <td>S3</td>
        <td>T3</td>
        <td>U3</td>

    </tr>

</table>

Answer №4

div.centeredAnchor
{
  width:calculateWidthRelativeToParent;
  margin-left:auto;
  margin-right:auto;
}

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

Autonomous boundary for list elements

I have a specific issue that can be observed in this fiddle: http://jsfiddle.net/h0qu4ffv/ where I set the margin-top of one list item to 50px, but all list items end up following this style. Is there a way to give each list item an independent margin, or ...

Fixed navbar does not collapse when clicking on items on a small-screen device

Currently, I am working with Bootstrap 4 and I was able to resolve a similar issue with Bootstrap 3. However, it seems that Bootstrap 4 is not behaving the same way. I am facing a roadblock and this is the final piece needed to complete the project. This ...

Angular styling and form error issue

Hey there! I'm new to Angular and facing a major issue along with a minor styling problem. Let's start with the big one: <mat-form-field appearance="fill"> <mat-label>Password</mat-label> <input matInput ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...

Navigating through a Collection of Pictures using Mouse Movement and Left-click Button

Trying to create a customized PACS viewer for scrolling through a series of CT head images. However, encountering an issue with scrolling through all 59 images. Currently, able to scroll from the first to the 59th image, but struggling to loop back to the ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

How can I combine multiple styles using Material-UI themes in TypeScript?

There are two different styles implementations in my code. The first one is located in global.ts: const globalStyles = (theme: Theme) => { return { g: { marginRight: theme.spacing(40), }, } } export const mergedStyle = (params: any) ...

Issue encountered with the carousel plugin while transitioning to a different page (utilizing Durandal)

I am currently working on a project using the Durandal SPA template, and I have integrated a carousel element into my page: var compositionComplete = function () { $('.testimonials-carousel').carousel({ namespace: "mr-rotato" // ...

Safari has no issues running Javascript, but other browsers are encountering failures

I am facing an issue where the code is working on Safari but failing on other browsers, and I can't figure out why. You can find the html part and the main javascript part. The main issue at hand is: When executing the function downloadurl(url, fun ...

JQuery click function not triggering the event

Here is the situation I am dealing with. On my index.php page, I have included the following JQuery code: jQuery(document).ready(function(){ jQuery('#sIMG img').click(function() { var currentSRC = jQuery(this).attr('src'); ...

Xpath: Determining the order of a tag in relation to text

Imagine there are two different snippets of HTML code as examples: <p>This is some text: <b>ABCD12345</b></p> <p><b>Name:</b> John Doe</p> I have the ability to separate the <b> and non-<b> sec ...

Search through a JSON array to find a specific element and retrieve the entire array linked to that element

Recently, I've been working with a json array that dynamically increases based on user input. Here's a snippet of the json code I'm dealing with: [{"scheduleid":"randomid","datestart":"2020-06-30",&quo ...

Verifying that the class name prefix aligns with the folder name using Stylelint

Currently, I am utilizing the "selector-class-pattern" rule from stylelint. My chosen pattern enforces the ECSS naming convention. The specific rule configuration is outlined below: "selector-class-pattern": ["^[a-z]([a-z0-9]){1,3}-[A-Z][a-zA-Z0-9]+(_[A-Z ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

Alter appearance of images depending on browser window size

I am working on an angular JavaScript code snippet that uses the ng-repeat command to display a row of small images. I want to ensure that these images do not spill over into a second line when the browser window is resized. Instead, I prefer them to eith ...

How do I test Pinia by calling one method that in turn calls another method, and checking how many times it has been called

As I embark on my journey with Vue 3 and Pinia, a particular question has been lingering in my mind without a concrete answer thus far. Let's delve into the crux of the matter... Here's an example of the store I am working with: import { ref, co ...

Incorporating multiple colors into a div with jQuery: A guide

I am looking for a way to create a legend by merging a specified number of colors within a div. I came across this useful Sample code that I have referenced. $.each(Array(50), function() { $("<div>").appendTo(document.body); }); var divs = $(&a ...

Issue encountered when invoking JavaScript from Angular TypeScript

I'm attempting to invoke a JavaScript function from within a TypeScript function, but it doesn't seem to be functioning properly. I've drafted some pseudo code on StackBlitz. Could you please take a look? https://stackblitz.com/edit/angula ...

PHP warning: Notice: Offset not defined

After creating an API to retrieve data from a database and display it as JSON in HTML, I encountered some PHP errors while trying to echo the data: Notice: Undefined offset: 80 in /opt/lampp/htdocs/ReadExchange/api.php on line 16 Notice: Undefined offse ...

Retrieve the Checked Value of a Checkbox Using Ajax Post in MVC

Can anyone provide assistance? This is the code I am working with: Index.cshtml <!DOCTYPE html> <html> <head> <title>jQuery With Example</title> @Scripts.Render("~/bundles/jquery") <script type="text/javascri ...