What is the best way to keep an image in place so that text doesn't shift it?

TLDR: I am struggling with keeping an image in place on my website while text is dynamically added to the screen above it using JavaScript.

In my coding course, we were tasked with creating a calculator that calculates total costs based on user input. I wanted to add a .gif below the calculator, but every time the total cost is displayed on the screen after submission, the .gif gets pushed down.

Although there is already space between the input/button and the .gif, the newly added text keeps moving the image further down. I have tried using <br clear="top"> and position: absolute, but neither seem to work. The JavaScript code responsible for displaying the message is impacting the position of the .gif which has automatic margins set in the CSS.

If you'd like to see the issue live, please visit: https://jsfiddle.net/6fom3syt/

Thank you for your help!

Answer №1

Here's a simple solution:

<p id="section-1">&nbsp;</p>

Make sure the p tag is not left blank.

Answer №2

To achieve your desired outcome, one of the simplest methods is to utilize the position: absolute property on the paragraph element. By applying position: relative to the container of the paragraph, using position: relative on the paragraph itself will make it relate directly to the container. With additional adjustments such as setting bottom: -3rem to move it below the input field and adjusting left along with translate to center it, you should be able to attain the layout you are aiming for.

var cost = 9.99;
var subtotal;

document.querySelector("#button-1").onclick = click
//console.log(document);

function click(){
    var i = document.querySelector("#input-1");
    var v = i.value;
    console.log(typeof(v));
    var subtotal = cost*v; //coercion
    var total = addTax(subtotal);
    total = total.toFixed(2);
    var message = "Your total for "+v+" shirts is $"+total;
    document.querySelector("#paragraph-1").innerHTML = message;


    //console.log("button has been clicked", v, subtotal, total);
    if(v==1){
        var message2 = "Your total for "+v+" shirt is $"+total;
        console.log(message2);
        document.querySelector("#paragraph-1").innerHTML = message2
    }
    else{
        console.log(message);
    }
}

function addTax(num){
    //var taxRate = 0.13;
    //var taxAmount = num*taxRate;
    //var total = num+taxAmount;
    var tax = 1.13;
    var total = num*tax;

    //console.log(total);
    return total
}
h1{
    color: antiquewhite;
    text-align: center;
    font-family: 'Georgia', Times New Roman, Times, serif;
}
#container{
    width: 70%;
    margin: auto;
    text-align: center;
    position: relative;
}
#paragraph-1 {
  position: absolute;
  bottom: -2.5rem;
  left: 50%;
  transform: translateX(-50%);
}

body{
    background-color: rgb(95, 147, 119);
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    color: antiquewhite;
}
button{
    background-color:rgb(95, 147, 119);
    color: antiquewhite;
    border-color: antiquewhite;
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    cursor:pointer;
}
input{
    background-color: rgb(95, 147, 119);
    color:antiquewhite;
    border-color:antiquewhite;
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
}
img{
    width: 50%;
    display: block;
    margin-left: auto;
    margin-right: auto;
}
<!DOCTYPE html>
<html>
    <head>
        <link rel = "stylesheet" type = "text/css" href = "m3.css">
    </head>

<body>
    <div id = "container">
        <h1 id= "mainHeading">module 3: functions</h1>
        <h2>How many shirts would you like to buy?</h2>
        <button id="button-1">submit</button>
        <input id="input-1" type="number">
        <p id="paragraph-1"></p>
    </div>
    <br clear="top">
    <p><img src = https://media3.giphy.com/media/3o6Mb7jQurR1B7mM5G/giphy.gif>
    </p>
    <script src="m3.js"></script>
</body>
</html>

(Ensure responsiveness or adjust text wrapping to avoid insufficient spacing between the input field and the image.)

Answer №3

Using CSS is one of the simplest ways to handle this issue. By setting a minimum height for elements like

, you can improve the overall UI appearance.

Check out this example on JSFiddle

#paragraph-1{
  min-height:30px;
}

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

Step-by-step guide to writing "<" and ">" symbols to a text file with a batch script

I have come up with a simple batch script to automatically format some HTML codes that I frequently use. Currently, I have to replace 888 and 999 with < and > respectively each time. I am aware that batch uses these symbols for redirection, so I am l ...

Is there JSON data available to determine the overall attendance rate in percentage?

I have a set of attendance data for a specific student. Each subject is marked with a 1 if the student was present, and a 0 if absent on a particular date. I need assistance in calculating the total attendance based on this information... { " ...

Achieving Vertical Alignment in Bootstrap 4: A Step-by-Step Guide

Bootstrap 4 has incorporated flex-box for vertical alignment now. Check out the details Here Even though I have Bootstrap Version 4.0.0-alpha.6 linked on my website, I am still unable to achieve the same layout as shown in the example above. This is the ...

Nest a Div inside another Div with a precise margin of 10 pixels

Recently, I attempted to create a fullscreen webpage like this one: https://i.sstatic.net/21KCr.png My goal was to have the color of each element change randomly every second. Here is the JavaScript code I implemented: <script> var tid = se ...

Mouseover function not triggering until clicked on in Google Chrome

I'm attempting to execute a function when the cursor hovers over a list item as shown below: <div id="vue-app"> <ul> <li v-for="item in items" @mouseover="removeItem(item)">{{item}}</li> </ul> </div> ...

Tips for compiling Bootstrap SCSS to specifically include only the extended classes

Is there a way to compile my custom bootstrap SCSS file into a CSS file that only includes the classes I created in my custom file? For example, I want to eliminate the extra CSS classes added to my HTML code. Instead of including unnecessary classes lik ...

Issues encountered while integrating react-digraph with VueJS

My goal is to utilize react-digraph in building a UI tool for managing parent-child hierarchies sourced from a database. The graphs should be interactive, editable, and able to handle multiple parent-child relationships. After researching various librari ...

Encountering an error in React js where it is unable to read property "0" when making an API call

I am facing an issue with accessing data from the fetch function in my project. The goal is to pass the data from the action to the reducer. The API is being called using a fetch function, which returns a promise. So, the API call is made separately and th ...

Tips for incorporating a Font Awesome icon <i> within a select dropdown and customizing its appearance

I am facing an issue while trying to insert an icon into a select option. The error message I received is: Warning: validateDOMNesting(...): cannot appear as a child of <option> To indicate that certain fields are required, I am using asterisk ic ...

Is it acceptable to place a <figure> tag inside a <header> tag within an <article>?

Imagine having this scenario: <article> <header> <h1>Article title</h1> <p>Article kicker</p> <figure> <img class="featured-image" src="http://article.com/featured/image. ...

How can one check in JavaScript if a specific URL was targeted with a XMLHttpRequest?

While I am familiar with monitoring network traffic in the browser's development tools and having XMLHttpRequests shown in the console, I am curious if there is a specific window property that showcases all network activity at once? ...

Adding a drop shadow effect to borders using CSS is a great way to

I created this unique button design using Figma and now I want to implement it in CSS. https://i.sstatic.net/b6hNx.png Upon closer inspection, you'll notice that I included a highlight with a white shadow on the border. However, when I try to repli ...

Unable to place text inside an image using Bootstrap

My issue pertains to text placement on images, which is behaving oddly in my code. The problem seems to stem from a hover system I have implemented, where the text only displays correctly when triggered by a hover event. My code snippet below addresses the ...

Quick fix for obtaining only one response

I'm facing a dilemma where I need to redirect the user to the dashboard page after they log in, but also send their JSON details to my client-side JavaScript. While I know that there can only be one res.send/end/json in a response and dynamic data can ...

Guide to adding a JS file from npm package to a new page in Nuxt.js

I am facing an issue where I have multiple npm packages containing client-side scripts that I need to include in different pages of my Nuxt.js project. I attempted to achieve this by using the following method: <script> export default { head: { ...

Understanding the source of an useEffect's trigger to create a conditional statement

Within my useEffect, I have two states included in the dependencies array: const [currentTab, setCurrentTab] = useState('open'); const [searchParams, setSearchParams] = useState(''); useEffect(() => { if (condition) { // logi ...

How can I use CSS to place a div at the bottom of its container?

I am trying to figure out how to use CSS to position a div at the bottom of its container, but the size of the container is not fixed. Can anyone provide some guidance on this issue? Thank you in advance for helping me solve this problem. You can check o ...

Remove all images within the HTML using jQuery

I have dynamically generated a div using the code snippet below: typebox.innerHTML += "<div id='idtypebox' class='typebox'><img id='typeImg' width='30px' height='30px' src="+d[o].src+"></div ...

Toggle the availability of links based on the presence of route parameters

My routing configuration appears as follows (for readability, I've omitted the second parameter in when()): app.config(function($routeProvider, $locationProvider){ // Prepare for html5 mode $locationProvider.hashPrefix('!'); $l ...

Is there a way to dynamically update the text of $ionicPopup's subTitle in Ionic?

I am currently attempting to modify both the value and style of the subText attribute linked to an $ionicPopup within my app. Despite searching extensively, I have been unable to uncover a viable method for accomplishing this task. Is there a way to achi ...