Leveraging jQuery for vertical alignment of an image

I am trying to vertically center an image with the class .personal within a container with the class .personal-row (located inside .row-main) on page load and when resizing. Initially, I attempted using vertical-align: middle;, but that did not yield the desired result. Instead, I tried calculating the height difference between the .personal and .row-main elements, dividing it by two, and then applying this calculated padding to the top and bottom of the image. This method theoretically should have vertically aligned the image. Furthermore, I only wanted this behavior to occur at desktop screen sizes, so I included a condition for that. However, upon resizing the window, I noticed that the padding became excessively large.

Below is the code I used:

$('.personal').css({'height':((0.5*$('.jumbotron').height())+'px')});
  if($(window).width() > 720){
    var originalPadding = (($('.row-main').height() - $('.personal').height()) / 2);
    $('.personal').css({'padding-top': originalPadding + 'px'});
    $('.personal').css({'padding-bottom': originalPadding + 'px'});
  }
  $( window ).resize(function() {
      $('.personal').css({'height':((0.5* $('.jumbotron').height()) +'px')});
      //row height - image height / 2 = padding
      if($(window).width() > 720){
        var centeredPadding = (($('.row-main').height() - $('.personal').height()) / 2);
        $('.personal').css({'margin-top': centeredPadding + 'px'});
        $('.personal').css({'margin-bottom': centeredPadding + 'px'});
      }
  });

The logic behind my approach seems sound in theory, but it is not functioning as expected. Can anyone provide assistance?

Thank you!

Answer №2

For those not supporting outdated browsers, it is highly recommended to utilize flexbox for improved performance and accessibility.

While the transition may not be significant on many devices, slower devices like mobile phones may experience issues when loading JavaScript later than intended, resulting in a choppy display of your page. Furthermore, relying on JavaScript for styling adds unnecessary calculations that most modern browsers can handle natively now.

Furthermore, keeping styling separate from JavaScript as much as possible is ideal for accessibility purposes, especially if a user's JavaScript is disabled or malfunctioning.

In terms of styling, assuming the content HTML structure is similar to:

<div class="jumbotron">
  <div class="personal-row">
    <img class="personal" src="..." />
  </div>
</div>

The corresponding CSS styles (including vendor prefixes) would be:

.personal-row {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
      -ms-flex-align: center;
          align-items: center;
}

Feel free to reach out if you have any inquiries!

Answer №3

If I were to choose, I'd go for CSS, however, you seem inclined towards using jQuery. Your code snippet looks like this:

$('.personal').css({'height':((0.5*$('.jumbotron').height())+'px')});

etc.

When setting CSS pixel sizes, it's typically necessary to enclose them in quotation marks (as strings), such as

$('.personal').css({'height':'48px'});

Alternatively, you can utilize a variable containing the string '48px', but not the string itself without quotes. My suggestion would be to use variables to obtain the height first, then calculate the new height and apply it like so:

var height1 = $('.jumbotron').height());
var height2 = 0.5 * height1 +'px';    
$('.personal').css({'height': height2});

(it may seem a bit complicated, but it does the job)

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

How to Align Paypal Button in the Middle of a Table Cell within a Concealed Form Using HTML and

Currently, I am in the process of developing a payment page that enables payments through Paypal using Instant Payment Notification. The initiation of this process involves sending a POST request to Paypal via a submit button along with multiple hidden for ...

Looping through RenderPartial with jQuery variables

I'm struggling to find a solution to this issue! On my page, there is a loop that calls a RenderPartial foreach(var item in Items) { Html.RenderPartial("Graph", item) } Within this RenderPartial, I am generating a graph var newGraph = new Grap ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

Unable to adjust iframe height

Below is a snippet of code that I am working with: <style type="text/css"> .div_class { position:absolute; border:1px solid blue; left:50%; margin-left:-375px; margin-top:100px; height:300px; width:500px; overflow:hidden; } .iframe_class { position: ...

Font Awesome icons within a nested accordion created using Bootstrap

I have a bootstrap accordion with 3 levels of nesting that is functioning correctly, but I want to make a change in the panel-heading div where I can use a font-awesome icon fa fa-chevron-down when the accordion is open (without affecting the nested accord ...

Overflow of dropdown menus in HTML CSS

Hello, I am new to both html and stack overflow. Please forgive me if this question has already been asked, as I couldn't find anything (but maybe I didn't search enough?). I have tried using overflow and clear properties, but I am struggling to ...

Determine which division is currently at the top of the scroll

I am having trouble retrieving the data attribute of each div with the class ".section" that has scrolled to the top. Currently, only the first div is being recognized, while the others at the top are not registering. Take a look at the example provided b ...

"Enhance your website with jQuery for a seamless

Here is some code I am working with: <div id="gallery"> <img src="image1.jpg" alt="Image 1"> <img src="image2.jpg" alt="Image 2"> <img src="image3.jpg" alt="Image 3"> </div> I am looking to display a standard animat ...

Troublesome situation created by JQuery AJAX incompatibility with Internet Explorer

I am currently working on a form that interacts with a SQL Table. JavaScript: <script> $(document).ready(function(){ function fetch_data() { $.ajax({ url:"select.php", method:"POST", cach ...

Trouble arises with saving sessions in IE and cakephp 1.3 through AJAX

Currently, I am in the process of creating an application using cakephp 1.3. In this particular project, there is a requirement where users need to select multiple items from various pages. To achieve this functionality, I am utilizing cakephp Session to m ...

The website is displaying a strange mix of text and HTML when viewed on a PC

While browsing the internet for C programs, I stumbled upon this particular program that caught my eye: <span style='color:#004a43'>#</span><span style='color:#004a43'>include</span><span style='color:#8 ...

Developing dynamic 3D cubes

In my latest project, I am attempting to construct a unique structure composed of 3D cubes arranged in a stacked formation. Each of the individual cubes within this structure is designed to be interactive for users. When a user hovers over a cube, it trigg ...

What is the best way to include a second (concealed) value in a cell using datatables

Query: How can I send specific cell values to a controller using POST method, where one value is visible and the other is hidden? For instance, each cell contains both Time and Date data but only the Time is displayed in the datatable. I need to post both ...

Steps for initiating an XMLHttpRequest in a XUL setting

When working in the XUL environment, I experimented with various methods using jQuery like this: $.ajax({ url:'http://www.X-site.com/api/call.php?q=test', success: function(){alert('success');}, error: f ...

Unlimited scrolling gallery with multiple rows

I am looking for a way to create a multi-row infinite loop scrolling gallery using html, css, and javascript. Can anyone help me with this? ...

Navigating the jQuery Search Form: Redirecting to Pages within your Website

After successfully creating my first Javascript search form with an Autocomplete Script, I am facing a challenge. I want to enable users to press "enter" after searching for a product and get redirected to the corresponding product URL page. The operation ...

The use of a Bootstrap row is leading to incorrect dimensions for FullPageJS

Within the body tag, I have included the following code snippet: <div id="container"> <div class="section profile"> <div class="row"> <div class="col-sm-6"> A </div> ...

What is the best way to set the width of an element to 100% while accounting for padding

My dilemma involves an HTML input field. The input currently has padding: 5px 10px;, but I need it to occupy 100% of its parent div's width (which is fluid). If I try using width: 100%;, the input ends up being wider than intended due to the padding ...

Modify the button's text with jQuery after it has been clicked

I've been struggling to update the text of a button after it's clicked, and I'm encountering an issue where it works in one part of my code but not in another. Could someone please guide me on what might be missing in my code? The first bl ...