The horizontal alignment of a jQuery div is off-center

There is a div element with a width: 50% and some text inside. Using jQuery, I am calculating the widths of both. Then, I attempted to horizontally center the text within the div using this jQuery code:

var wrapperWidth = $("#wrapper").width();
var textWidth = $("#text").width();
var horAlign = wrapperWidth / 2 - textWidth;
$("#text").css("margin-left", horAlign);

I basically tried to mimic

margin-left: calc(mydiv - mytext)
in CSS. However, the issue is that the text doesn't appear centered. You can view the problem on this fiddle:

var r = (function () {
  var wrapperWidth = $("#wrapper").width();
  var textWidth = $("#text").width();
  var horAlign = wrapperWidth / 2 - textWidth;
  $("#text").css("margin-left", horAlign);
  
  var textHeight = $("#text").height();
  var vertAlign = textHeight / 2
  $("#text").css("margin-top", - vertAlign);
});

$(document).ready(r);
$(window).resize(r);
#wrapper{
  width:50%;
  height:400px;
  border:solid 5px black;
  margin:auto;
  margin-top:50px;
}

#text{
  font-family: Helvetica, Arial, Sans-Serif;
  font-weight:bold;
  text-transform:uppercase;
  font-size:3.5em;
  padding-left:30px;
  padding-right:30px;
  background:white;
  display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
   <p id="text">Test</p>
</div>

What mistake have I made here?

Answer №1

Why not consider a pure CSS solution?

#container{
  width:75%;
  height:300px;
  border:solid 3px black;
  margin:auto;
  margin-top:30px;
}

#content{
  font-family: Times New Roman, Times, Serif;
  font-weight:normal;
  text-transform:none;
  font-size:1.5em;
  display: block;
  text-align: center;
}

#content span {
  position: relative;
  top: -20px;
  display: inline-block;
  padding-left:10px;
  padding-right:10px;
  background: lightgrey;
}
<div id="container">
   <div id="content"><span>Example</span></div>
</div>

Answer №2

Made some adjustments to your code and now the text has padding, so you'll need to use the innerWidth() function to calculate the width of the text including the padding. Hope this explanation clears things up for you :)

var r = (function () {
  var wrapperWidth = $("#wrapper").width() / 2;
  var textWidth = $("#text").innerWidth() / 2;
  var horAlign = wrapperWidth - textWidth;
  $("#text").css("margin-left", horAlign);
  
  var textHeight = $("#text").height();
  var vertAlign = textHeight / 2
  $("#text").css("margin-top", - vertAlign);
});

$(document).ready(r);
$(window).resize(r);
#wrapper{
  width:50%;
  height:400px;
  border:solid 5px black;
  margin:auto;
  margin-top:50px;
}

#text{
  font-family: Helvetica, Arial, Sans-Serif;
  font-weight:bold;
  text-transform:uppercase;
  font-size:3.5em;
  padding-left:30px;
  padding-right:30px;
  background:white;
  display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
   <p id="text">Test</p>
</div>

Answer №3

Modify your calculation like so:

var horAlign = wrapperWidth / 2 - textWidth / 2;

Additionally, remove the padding property as it interferes with alignment.

var r = (function () {
  var wrapperWidth = $("#wrapper").width();
  var textWidth = $("#text").width();
  var horAlign = wrapperWidth / 2 - textWidth / 2;
  $("#text").css("margin-left", horAlign);
  
  var textHeight = $("#text").height();
  var vertAlign = textHeight / 2
  $("#text").css("margin-top", - vertAlign);
});

$(document).ready(r);
$(window).resize(r);
#wrapper{
  width:50%;
  height:400px;
  border:solid 5px black;
  margin:auto;
  margin-top:50px;
}

#text{
  font-family: Helvetica, Arial, Sans-Serif;
  font-weight:bold;
  text-transform:uppercase;
  font-size:3.5em;
  //padding-left:30px;
  //padding-right:30px;
  background:white;
  display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
   <p id="text">Test</p>
</div>

Answer №4

The crucial aspect you overlooked is the necessity to divide textWidth by 2:

var horAlign = wrapperWidth/2 - textWidth/2; // Make sure to update your code accordingly.

Answer №5

Here is a suggestion for achieving the desired outcome:

let wrapperWidth = $("#wrapper").width();
let textWidth = $("#text").width();
let paddings = 60;
let horAlign = (wrapperWidth - textWidth - paddings)/2;

Don't forget to account for the padding! Consider assigning a value to the variable 'padding' as well.

Answer №6

width() allows you to get the width without considering the padding. Therefore, it is important to adjust your calculations to take padding into account as well:

Additionally, the formula for center aligning would need to be adjusted.

var r = (function() {
  var wrapperWidth = $("#wrapper").width();
  var textWidth = $("#text").width() + parseInt($('#text').css('padding-left')) + parseInt($('#text').css('padding-right'));

  var horAlign = (wrapperWidth / 2) - (textWidth / 2);

  $("#text").css("margin-left", horAlign);

  var textHeight = $("#text").height();
  var vertAlign = textHeight / 2
  $("#text").css("margin-top", -vertAlign);
});

$(document).ready(r);
$(window).resize(r);
#wrapper {
  width: 50%;
  height: 400px;
  border: solid 5px black;
  margin: auto;
  margin-top: 50px;
}

#text {
  font-family: Helvetica, Arial, Sans-Serif;
  font-weight: bold;
  text-transform: uppercase;
  font-size: 3.5em;
  padding-left: 30px;
  padding-right: 30px;
  background: white;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <p id="text">Test</p>
</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

Creating a line chart with multiple axes using Chart.js by importing data from a Google Sheet in JSON format

My attempt to visualize the data stored in a Google Sheet using Chart.js resulted in a multi-axis line chart. The data I have looks like this: https://i.stack.imgur.com/F8lC7.png When trying out the following code, I encountered an issue where only the f ...

Ways to guide users through a single-page website using the URL bar

I currently have a one-page website with links like <a href="#block1">link1</a>. When clicked, the browser address bar displays site.com/#block1 I am looking to modify this so that the browser shows site.com/block1, and when the link is clicke ...

Is the execution of renderer.render() synchronous or asynchronous?

In my quest to capture a screenshot after each rendered frame, I have noticed some duplicates. This has led me to suspect that I may be saving the screenshot before the rendering process is fully completed. Therefore... Is it possible for renderer.rend ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

What is the method to execute a prototype function within another prototype?

I am facing an issue with my JavaScript class and need some help to resolve it. MyClass.prototype.foo = function() { return 0; } MyClass.prototype.bar = function() { return foo() + 1; } Unfortunately, when I try to run the program, it throws an ...

Hexagonal design reminiscent of a beehive

I am struggling with implementing a specific layout using grid CSS and I'm open to using flex or any other method. .container { display: grid; grid-template-columns: repeat(auto-fit, 50px); grid-template-rows: repeat(auto-fit, minmax(80px, 80px)); ...

jquery toggle not working on second click

I need to constantly repeat two functions, but I am experiencing issues: function rotation () { plrotation(); function plrotation () { alert('pl'); $('#pl').toggle(300).delay(10000).toggle(40 ...

Displaying a PDF file by clicking a button using AJAX

https://i.sstatic.net/6O9rm.jpgI am facing an issue with opening a PDF file on click of a button. Despite trying to achieve this using AJAX, the PDF file does not open. Whenever I click the View PDF button, I keep getting an alert message. Below is the AJ ...

Failure to pass a variable declared within a function to another JavaScript file running simultaneously

After combing through numerous posts on Google and Stack Overflow, I am still unable to pinpoint why this particular issue persists. This case involves 2 HTML files and 2 JS files (explanations provided below in text following the code snippets). 1) inde ...

Async reaction in MobX is a powerful tool for handling

Hey there, I am currently utilizing MobX in a store and faced with the need for an asynchronous reaction to occur when a computed value changes: class Store { @observable user; @observable something; @computed get firstParam () { ret ...

Change a camelCase string to ALL_CAPS while adding underscores in JavaScript

Currently, I'm dealing with a situation where I have a list of variables stored in a file that I need to convert into all capital letters and separate them with underscores using JavaScript. The variable pattern looks something like this: AwsKey Aw ...

Controlling HTML components without using the runat="server" attribute

It's just a dream for now; it's not reality. Homepage.aspx <ul id="menumenu" runat="server"> <li><a href="www.google.com">google</a></li> <li><a href="www.yahooo.com">yahooo</a></li> ...

Should buttons be wrapped based on the text of the link?

I'm struggling to include buttons in my design but I can't seem to achieve the desired outcome. The image below illustrates what I am attempting to create but have been unsuccessful in replicating: https://i.sstatic.net/CnYLV.png However, the ...

Problems with radio button serialization in jQuery form plugin

I've created a basic form: <form class="dataform" method="post" id="settings" action="/"> <input type="radio" name="shareSetting" value="n"/> <input type="radio" name="shareSetting" value="y"/> <input type="button" na ...

Tips on implementing ng-template within an Angular application

I'm in the process of developing a client-side angular application and have encountered an issue regarding the implementation of angular's ng-template. Currently, I have a navbar set up as follows: <nav class="navbar navbar-inverse" > ...

How can I forward a post request to a different URL in a node.js application?

I am attempting to forward a POST request from one server to another server while including additional parameters from the initial request. Take a look at the code snippet below. app.use(bodyParser.urlencoded({ extended: true })); app.post('/pay1&ap ...

Attempting to proceed to the next prompt in the questioning sequence based on the user's choice

Hey there, I'm currently a bootcamp student and I'm working on creating a team profile. I'm facing an issue with the code related to adding engineers to the team. After inputting manager information, I should be able to choose to add an engi ...

The process of verifying email addresses using Angular 5

I'm having trouble validating my email with the .com domain. I've tried various methods, but so far, none have worked. Can anyone provide guidance? I'm new to Angular and struggling with this particular issue. Ideally, I want the email to be ...

What is the best way to align the logo image in the center of the header vertically?

I am trying to vertically center my logo, but I have not been successful with using margin: auto or margin: center. Here is what I have tried so far: ・text-align: center; ・margin: auto; ・margin: center: ・navbar-brand-center The logo currently app ...

What is the best way to make my <div> element expand to fill the entire width of the screen? I attempted setting the width to 100%, but it didn

I need help creating a <div> that spans the entire width of the screen. In my CSS, I have this code: #spacer3 { width:100%; height:300px; } Although it seems like it should work, the div is not extending all the way to the edges of the screen on ...