Unusual div image alignment when dimensions are dynamically adjusted with Javascript animations

I have created a basic webpage using JavaScript that aims to scale an element from the center of the page over time when clicked. It is functioning properly for the SVG element I tested it with.

However, when I use an image, it initially appears outside of the centered div and gradually moves towards it as it enlarges, eventually getting centered as intended. Despite setting overflow to hidden, the image remains visible outside of the div. The div is always resized first and should be large enough to contain the image.

Could this issue be due to the small size values I am utilizing, or is there a flaw in my code?

<!DOCTYPE html>
<html>
  <head>    
    <style>
    body {
     margin:0;
    }
    #maindiv {
     position:absolute;
     background-color:#141414;
     width:100%;
     height:100%;
     overflow: hidden;
    }
    #face {
    width:109px;
    /* height: auto !important;  */
    }
    #facediv { 
     position: absolute; 
     top: 50%; 
     left: 50%;
     }
    </style>

    <script>

    function sizeUpdate (elem){
        var sf = 1

        function frame(){

            sf++                                                                <!-- increment scale factor
            var fwidth = 0.1;
            var scaledwidthface = (fwidth * sf);                              <!-- scaled width - width-constant*scale-factor
            var face_var =document.getElementById("face");
            var facediv_var = document.getElementById("facediv");
            facediv_var.style.width = ""+scaledwidthface+"px";                <!-- set containing div to same width as object
            facediv_var.style.marginLeft = ""+(-1 * scaledwidthface/2 )+"px"; <!-- set the container div to x-offset half object-width (centres horizontally)
            face_var.style.width = ""+scaledwidthface+"px";                  <!-- set width of object
            var face_ht = face_var.clientHeight;                              <!-- get integer-form of object height (?)
            facediv_var.style.height = ""+face_ht+"px";                       <!-- set container div to same height as object
            facediv_var.style.marginTop = ""+(-1*face_ht/2)+"px";             <!--set container div y-offset half object-height (centres vertically)

            if (sf == 500)
                clearInterval(id)                                             <!--stop when incr reaches this maximum
        }

        var id = setInterval(frame, 50)

    }
    </script>
 </head>


    <body>
        <div id="maindiv" onclick="sizeUpdate(this.children[0])">
            <div id="facediv">
                <img id="face" src="http://goo.gl/6xLiC">
            </div>
        </div>
    </body>
</html>

Answer №1

The issue at hand arises from the default inline display of images, which causes them to inherit attributes like font-size and line-height. The discrepancy you observed can be resolved by adding the display:block rule to the CSS.

#facediv img {
    display:block;
}

Check out the Demo for a visual representation.

Apologies for not catching this sooner :P

EDIT: Just for fun, I created an alternative version where the image remains inline but with a line height and font size set to 0px. Feel free to test it in this demo.

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

Customize the antd theme in a create-react-app project without the need to eject webpack

Struggling with customizing antd in my react app. I'm hesitant to mess with the webpack config.js file since I'm not well-versed in webpack. My goal is to avoid having a site that looks like a generic antd clone, but all my attempts at customizat ...

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...

Manipulate documents in a Mongoose array by conditionally adding or removing elements

Upon receiving data from the front end, I am dealing with the following object: { name: "Test 1", sets: [1,2] } Mongo Schema: Sets name: { type: String }, tests : [{ type: Schema.Types.ObjectId, ref : 'Test' ...

Analyzing the functionality of Express with Mocha and Chai

Currently facing an issue with testing my express server where I am anticipating a 200 response. However, upon running the test, an error occurs: Test server status 1) server should return 200 0 passing (260ms) 1 failing 1) Test server statu ...

Obtain the name of the checkbox that has been selected

I'm new to JavaScript and HTML, so my question might seem silly to you, but I'm stuck on it. I'm trying to get the name of the selected checkbox. Here's the code I've been working with: <br> <% for(var i = 0; i < ...

Display the results of a PHP-MySQL query within an HTML dropdown list

In my database, I have two tables called groups(groupID, groupName) and userBelongToGroups(userID, groupID). groups userBelongToGroups =================== ===================== groupID | groupName userID | groupID --- ...

What is the best way to change the font size in HTML?

https://i.sstatic.net/IjLvn.png After carefully analyzing the image provided, I encountered an issue while attempting to incorporate the code display:block. However, no changes were reflected. Can you identify what may be causing this discrepancy in my te ...

Overlap one element entirely with another

Currently, I am working on a way for an element called overlayElement to completely cover another element known as originalElement. The overlayElement is an iFrame, but that detail may not be significant in this scenario. My goal is to ensure that the over ...

Is there a way for me to know when ng-options has completed updating the DOM?

I am currently working on integrating the jQuery multiselect plugin using a directive within my application. Here is the select element: <select multiple ng-model="data.partyIds" ng-options="party.id as party.name for party in parties ...

Switch up the styling of a component by updating its properties with a switch statement

Although there is a similar question, my query has a unique requirement. I have defined the common styles for my button and implemented a function using a switch statement with different properties for various buttons across different pages. However, for ...

Can jQuery Autocomplete function without stopping at white spaces?

Is there a way to modify jQuery UI autocomplete so that it can handle multiple words instead of terminating with a space? For example, if you input "New York City", it should still filter results based on each word. $.ajax({ type: "GET" ...

There is an issue showing up in the console: $(…).datepicker is not defined as a function

I am new to using HTML with JavaScript. I attempted to implement a datepicker, but unfortunately, it is not working as expected. The error message I am receiving is '$(...).datepicker is not a function' in the console. I am utilizing multiple f ...

The ajax request does not support this method (the keydown event is only active during debugging)

I've encountered a strange issue with an AJAX request. The server-side code in app.py: #### app.py from flask import Flask, request, render_template app = Flask(__name__) app.debug = True @app.route("/myajax", methods=['GET', ...

What is the best way to use AJAX to update multiple items with a common customer number on a SharePoint list?

Currently, I am facing an issue while attempting to update a SharePoint list using JavaScript/ajax. The script is running smoothly until it reaches the ajax function, where it encounters a failure. Specifically, it mentions that the ItemID is not defined, ...

Issue with Cross Site Scripting Iframe Permission Denied

I'm encountering a Cross Site Scripting error when using the code below. Javascript function resizeIframe(ifRef) { var ifDoc; //alert(ifRef); try { i ...

Update the headers of the axios.create instance that is exported by Axios

I have a single api.js file that exports an instance of axios.create() by default: import axios from 'axios' import Cookies from 'js-cookie' const api = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 10000, headers ...

Reviewing the element names in a jQuery-selected array of objects

I'm new to javascript and the jquery library and I need to work with an array of input fields that have specific names for validation. Each input field is named NS[0], NS[1], etc., and the total number of these fields is generated dynamically in the c ...

How can we add a class to a radio button using jQuery when it is checked, and remove the class when it

I'm looking for help with using jQuery to toggle between two radio buttons and display different divs based on the selection. jQuery(document).ready(function($) { if ($('#user_personal').is(':checked')) { $('.user_co ...

Modifying Label text dynamically using jQuery on Click event

My website HTML contains the following code snippet: <script src="js/jquery.flexslider.js"></script> <script src="js/jquery.rings.js"></script> The contents of jquery.rings.js are as follows: $('input[type="image"]') ...