How can you make an element be positioned in the center

Suppose I have a series of links like:

<a>foobar</a><a>foobar</a><a>foobar</a><a id="center">foobar</a><a>foobar</a>

If one of them has an id="center", is it possible to position it in the center using JavaScript or CSS?

Answer №1

When dealing with DOM-locality...

To manipulate the DOM, you will likely need to use scripting to reference and modify the elements you are interested in. It could involve selecting certain links by container or common classname, then inserting a new link at a specific position based on the total number of links.

$(function(){
 var bodyLinks = $("body a");
 var halfPoint = Math.floor(Number(bodyLinks.length/2)-1);
 $("body a:eq("+halfPoint+")").after($("#center"));
});​

Check out the online demo: http://jsbin.com/aroba/edit

For CSS-placement:

$(function(){
  var elWidth = $("#center").width();
  var elOffset = $("#center").offset().left;
  var wnWidth = $("body").width();
  var sibWidths = 0;
  
  $("#center").prevAll("a").each(function(){
    sibWidths += $(this).width();
  });
 
  var gutter = ((wnWidth-elWidth)/2)-sibWidths;
  
  $("body p:first").css({paddingLeft:gutter});
  
});

See the online demo: http://jsbin.com/oniba/edit

Answer №2

It seems like your question is missing some specifics, but here's a suggestion that could be helpful:

$("#center").css({
    position: "absolute",
    left: function () { 
        return (this.offsetParent.offsetWidth - this.offsetWidth) / 2 + "px";
    }
});

Answer №3

UPDATED: Here is a different perspective:

<html>
<head>
    <title>StackOverflow</title>
    <style type="text/css">
        td{
            padding:0;
        }
        .left{
            width: 49%;
            text-align:right;
        }
        .right {
            width: 49%;
            text-align:left;
        }
        .middle {
            width: 2%;
            text-align:center;
            background:#DEF;
            white-space:nowrap;
        }
        td div {
            overflow: hidden;
            height:1.2em;
        }
    </style>
</head>
<body>

</head>
<body>
    <table>
        <tr>
            <td class="left"><div><a>left item 1</a><a>left item 2</a><a>left item 3</a><a>left item 4</a><a>left item 5</a><a>left item 6</a><a>left item 7</a><a>left item 8</a></div></td>
            <td class="middle"><a>centered</a></td>
            <td class="right"><div><a>right item 1</a><a>right item 2</a><a>right item 3</a><a>right item 4</a><a>right item 5</a><a>right item 6</a></div></td>
        </tr>
    </table>
</body>
</html>

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

Node-powered Angular

Currently working on setting up client-side routing with AngularJS and Node. Ran into some issues along the way. EDIT After making changes to my code based on recommendations from @PareshGami, following https://github.com/scotch-io/starter-node-angular, I ...

Tips for enabling the wrap property with autogeneratecolumn set to true

In my grid view, I want to ensure that any text in a column that exceeds the width of the column will either wrap within the column or display on a new line. Below is the code for the grid view: <asp:GridView ID="GridView1" AllowSorting="True" runa ...

Changing a class and audio and storing it using browser's local storage

The challenge I am facing: I am currently working on a feature for my website that allows users to toggle the volume on/off and have that setting persist across different pages. Specifically, I want the user's volume preference to be saved when they n ...

What causes the conflict between Nodejs usb module and Electron?

Apologies for the lengthy post, but I've been tirelessly searching for a solution online without any luck. My goal is to create a basic Electron application that can display an HTML page (which is working fine) and control a printer through the USB mo ...

Aligning a button with a <div> block is not achieved through styling

Take a look at the jsfiddle example. Expected result: Actual result: Here is the HTML snippet responsible for that section of the page: <input type="submit" name="BT_resetZoom" value="Reset coordinates" id="BT_resetZoom" tabindex="10" style="height: ...

Issue with Foundation4 Dropdown Persisting Despite Different Behavior Between Two CSS Files

My project involves having two CSS files, both compiled from SASS, that cater to right-to-left (RTL) and left-to-right (LTR) designs. Additionally, there are two separate HTML files, each referencing the corresponding CSS file: RTL: <link rel="stylesh ...

What is the significance of :: in AngularJS?

When reviewing certain Angular JS files, I often come across the following syntax. What is the significance of a double colon "::" in this context? <span>{{::x}}</span> <div>{{::y.z()}}</div> ...

React is encountering a problem with loading the image source and it is

<img src="play.jpg" alt="play"></img> This code works fine in standard HTML, but I'm having trouble getting it to work in React. Is adding it as a background the only solution? ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

Alter the CSS of a <div> element upon clicking on it

Is there a way to dynamically adjust the width and height of this div element after it is clicked, essentially treating it like a button? The current HTML structure is as follows: <div class="sq" onclick="main.function();"> ... </div> Below ...

Leverage the Power of Mongoose Schema Across Various Files (mongoose)

I recently encountered an issue while trying to utilize my Permissions schema in two different files. The error message "Cannot overwrite 'example' model once compiled" keeps popping up. Query: How can I effectively employ my Permissions schema ...

"AngularJS Bi-Directional Data Binding Issue: Unexpected 'Undefined

Recently, I've been tackling a project that involves using a directive. Initially, everything was smooth sailing as I had my directive set up to bind to ngModel. However, I hit a roadblock when I needed to bind multiple values. Upon making the necessa ...

Executing Javascript on Selenium RC with PHP is a crucial skill to have in your toolkit

Is there a way to execute Javascript from Selenium RC? I have been trying different methods with no success so far. I attempted the following approach: I created a custom function in user-extensions.js: function sayhello() { document.write('hel ...

The format of the date cannot be modified when using DesktopDatePicker as a React Component

I've been attempting to modify the appearance of the component, but the UI keeps showing the date in month-year format. <DesktopDatePicker inputVariant="outlined" label="Pick-up date" id="date ...

Exploring the power of makeStyles in Material UI when combined with TypeScript

I am currently in the process of converting a JavaScript template to Typescript. Here is an example of my accordionStyle.ts file: import { primaryColor, grayColor } from "../../material-dashboard-pro-react"; const accordionStyle = (theme?:an ...

Design a button for removing the selected value in select2

Can anyone provide some guidance on using select2? I am working with 2 select2 elements, and I want the selected value to be displayed on a button instead of in the input area of the select2. This way, the select2 will still display the placeholder text. ...

Securing API endpoints in a React/Redux application using proxy techniques

Ensuring the security of my react/redux application is a top priority for me. I've noticed that my api url is exposed to the public inside the bundled app.js file, which raises some concerns. After doing some research, I discovered that some developer ...

Submit additional data along with the form to the server

Is there a way to send both form data and additional values (such as {a:'A',b:'B',c:'C'}) to the server using jQuery ajax? The HTML code: <form id="myForm"> <p>firstname: <input name="firstname" type="text ...

Challenge with Dependency Injection in the Handlers of NestJS CQRS repositories

As a newcomer to nodejs, I am currently delving into the implementation of NestJS's CQRS 'recipe'. In my service, I have a Request scoped with the injection of QueryBus: @Injectable({scope: Scope.REQUEST}) export class CustomerService { co ...

Gather information on a webpage

I am attempting to extract a table from the following page "https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Statistics/Historical-Monthly?sc_lang=en#select1=0&select2=0". After using the inspect/network function in Chrome, it appears that the data ...