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

Issues with clearRect() function in HTML5 canvas

Recently, I developed a function with the goal of redrawing a square line block that covers the entire page whenever the window size is adjusted. For reference, you can view my code at http://jsfiddle.net/9hVnZ/ However, I encountered an issue: bgCtx.cl ...

Activate animation when a user clicks on a link

Hey there, I'm a bit unsure about how to word this and I'm still getting the hang of StackExchange so I hope I've posted in the correct place. Currently, I am developing a mobile HTML5 app that utilizes Phonegap/Cordova (as well as Bootstra ...

Execute Yarn commands from the main directory

In the midst of my project, I have various sub projects - one of which is dedicated to JavaScript. My intention is to employ this JavaScript project as a task runner for the entire endeavor using gulp. However, I've hit a snag in the process. The lay ...

The arrangement of a table, an iframe, and another table being showcased in close proximity

I need assistance in aligning a table, an iframe, and another table side by side without any breaks. Ideally, I would like all three elements to be centered on the page. It seems odd that they're not displaying next to each other as my screen is larg ...

Dependency tree resolution failed during VUE installation

After pulling my project from another computer where it worked fine, I encountered an error when trying to npm install on this machine. Can someone please provide some guidance on how to resolve this issue and prevent similar problems in the future? npm ER ...

Sorting elements in an array based on an 'in' condition in TypeScript

I am currently working with an arrayList that contains employee information such as employeename, grade, and designation. In my view, I have a multiselect component that returns an array of grades like [1,2,3] once we select grade1, grade2, grade3 from the ...

What methods can I use to test a Django view that includes a form?

As I embark on developing an application using Django, I find myself faced with a particular challenge. I have created a view that receives a form from the HTML code and then searches the database for any instances of a model based on the values specified ...

BorderWoocommerce

Something odd has appeared around my shopping cart total ("WARENKORB SUMME") today. Could you please take a look at the screenshot below? Any idea how to remove it? This is for a Wordpress/WooCommerce store. I haven't made any recent changes - I su ...

Retrieving an array of various responses using Axios

My current code includes a function that retrieves exchange rates for various stocks: export const getRates = (symbole1, symbole2, symbole3) => { const res = [] axios.all([ axios.get(`${baseUrl}/${symbole1}`), axios.get(`${ ...

The jQuery click function triggers immediately upon the loading of the page

Despite my best efforts to resolve this issue independently and conduct extensive research on Google, I am still unable to identify the root of the problem. It seems that the click function continues to activate upon page load. Kindly elucidate the under ...

What is the procedure for extracting data from a JSON file within an HTML document?

Hey there, I am currently working on reading data from a json file using ajax. I have created a Video object that consists of Courses objects with titles and URLs. However, when attempting to read the title and URL of HTML as an example, I am not seeing a ...

When a child component sends props to the parent's useState in React, it may result in the return value being undefined

Is there a way to avoid getting 'undefined' when trying to pass props from a child component to the parent component's useState value? Child component const FilterSelect = props => { const [filterUser, setFilterUser] = useState('a ...

Styling the navigation bar using CSS and positioning a <div> element underneath

Struggling to design a navbar using Bootstrap and have a div positioned underneath it that fills the remainder of the page? You're not alone! As someone new to Bootstrap and CSS, this can be tricky. Here's an example of how I created a navbar: ...

converting JSON to date format in angular

.controller('feedCtrl', ['$scope', '$http', function($scope, $http) { $http.get('items.json').then(function(response) { $scope.items = response.data; $scope.user = localStorage.getItem("glittrLoggedin"); ...

Is there a way to exclude certain URLs from the service worker scope in a create react app, without the need to eject from the project?

Is there a way to remove certain URLs from a service worker scope in create-react-app without needing to eject? The service worker is automatically generated, and it seems impossible to modify this behavior without undergoing the ejection process. ...

Uploading with Javascript CORS consistently ends with an error event occurring

My current challenge is uploading a file to a server using JavaScript in compliance with the CORS specification. While there are numerous examples available online that successfully upload the file, I encounter an error as the final event being fired. Up ...

The deployment on heroku encountered an error during the build process

I'm attempting to deploy my React application on Heroku, but I keep encountering the following errors: -----> Installing dependencies Installing node modules npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ...

The main source for loading the 'XYZComponent' cannot be located

There's an issue I'm facing where ng2 code is being loaded into a .Net MVC component, but the console is showing the following error: EXCEPTION: Uncaught (in promise): Error: Cannot find primary outlet to load 'UsersComponent' Error: C ...

Break the line using HTML select option and set it as the value

I am working on a select box where I want to include a value for a line break. <select> <option value=";">Semicolon</option> <option value=",">Comma</option> <option value=".">Dot</option> <opti ...

What is causing this console to output twice?

My Objective: I aim to utilize Node.js to launch two child processes sequentially at a specific time, displaying their `stdout` as it streams, occasionally alternating between the two processes. The Desired Output: `Proc 1 log # 1` `Proc 1 log # 2` `Pr ...