Contrasting behavior shifts between in-line style declaration and class usage

My goal is to create a grid of boxes, each containing information about different dog breeds. However, I've encountered an issue with styling that has left me puzzled. When I apply a style in-line versus using the same style within a class, the behavior seems to differ unexpectedly. This inconsistency is confusing to me and goes against what I understand about CSS.

The code functions correctly when styled as shown here: https://i.sstatic.net/VIK6l.jpg In this case, pay attention to the "dogDisplay" class defined in the style section, along with the div element assigned the "dogDisplay" class in the body. Additionally, note that the div has an in-line style attribute set to "position:absolute".

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

   <link href="bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<style>
    .dogDisplay {
        display: inline-block;
        width: 300px;
        height: 300px;
        margin: 10px;
        background-color: grey;
    }

    .dogName {
        font-size: 20px;
        text-align: center;
    }

    .img {
        width: 200px;
        height: 200px;
        display: block;
        margin-left: auto;
        margin-right: auto; 
    }

    .content {
        background-color: red;
    }

</style>

</head>

<script>
    //This loads dog information from a JSON file
    var dogInfo = [];

    function displayInfo(dogBreeds) {
        $("#container").append("<div class='dogDisplay'></div>");
    }

    window.onload = function() {

        $.getJSON("breeds.json", function(json) {
            var i;
            console.log(typeof(json.dogBreeds));
            dogInfo = json.dogBreeds;
            displayInfo(json.dogBreeds);
        })
    }

</script>

<body>

    <div class="well" style="height:300px"></div>

    <div id="container" class="container" style="width:100%;background-color:lightblue;border:black 2px solid;">
        <div class="dogDisplay" style="position:absolute">
            <div class="content">
                <p class="dogName">Dog Name</p>
                <img class="img" src="images/place-holder.jpg" alt="Place-holder">
            </div>
        </div>
    </div>
</body>

However, if I move the style rule "position:absolute" into the ".dogDisplay" class, the behavior changes as depicted in this image: https://i.sstatic.net/iuOVM.jpg

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<style>
    .dogDisplay {
        display: inline-block;
        width: 300px;
        height: 300px;
        margin: 10px;
        background-color: grey;
        position: absolute;
    }

    .dogName {
        font-size: 20px;
        text-align: center;
    }

    .img {
        width: 200px;
        height: 200px;
        display: block;
        margin-left: auto;
        margin-right: auto; 
    }

    .content {
        background-color: red;
    }

</stytler

</head>

<script>
    var dogInfo = [];

    function displayInfo(dogBreeds) {
        $("#container").append("<div class='dogDisplay'></div>");
    }

    window.onload = function() {

        $.getJSON("breeds.json", function(json) {
            var i;
            console.log(typeof(json.dogBreeds));
            dogInfo = json.dogBreeds;

            displayInfo(json.dogBreeds);
        })

    }

</script>

<body>
    <div class="well" style="height:300px"></div>
    <div id="container" class="container" style="width:100%;background-color:lightblue;border:black 2px solid;">
        <div class="dogDisplay">
            <div class="content">
                <p class="dogName">Dog Name</p>
                <img class="img" src="images/place-holder.jpg" alt="Place-holder">
            </div>
        </div>
    </div>
</body>

This difference in behavior has left me scratching my head. If anyone can shed light on why this occurs, I would greatly appreciate it!

Answer №1

When looking at your first scenario, a conflict arises between the following line of code:

$("#container").append("<div class='dogDisplay'></div>");
and the initial layout:
<div class="dogDisplay" style="position:absolute">

This implies that only the original .dogDisplay will be positioned absolutely. However, in the second example, every instance will have absolute positioning.

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

Trigger a click event on a dynamically loaded button

Here's a unique twist to the usual discussions on this topic. I have a dynamically loaded button in my HTML, and I've saved the selector for it. Later on in my code, I need to trigger a click event on this button programmatically. The typical $(& ...

I'm having trouble retrieving the index of the map function within a function called by a button onClick() event, all of which is contained within the scope of the

Initial State const [variationData, setVariationData] = useState([ { name: "", value: [""], }, ]); Function Triggered by Button Click const addValueField = (e, index) => { e.preventDefault(); const fiel ...

Establish a function within an interface using the name obtained from a constant in Typescript

How can I define functions within an interface using constants as function names? I have a const array containing event names and I want to create an ServerToClientEvents interface for SocketIO. I can define a function like this and it will work: interfac ...

What steps can be taken to resolve the error message "Path must be a string. Received undefined" that is occurring in webpack4 with the copy-webpack-plugin?

I am currently working on setting up a separate file in webpack to handle the copying of static assets from the src folder to the web folder. Versions: node: 8.15.0 yarn: 1.13.0 webpack: 4.19.1 copy-webpack-plugin: 6.0.0 In my existing project structure, ...

Node.js Buffer problem: How to tackle it

Encountering an issue with buffers in Node.js The constant buffer is defined as follows: var commands = { BufferOne : new Buffer([0XCA, 0X11, 0X00, 0X00, 0X60, 0X01, 0X00, 0X01, 0X08, 0X07, 0X6D, 0X00, 0X00, 0X00, 0X00, 0 ...

Add a touch of mystery to a triangle SVG with CSS shadows

Is there a way to apply shadows to SVG images, like a triangle? I've tried using polyfill solutions but they didn't give me the desired effect. Check out this JSFiddle where I showcase what I'm trying to achieve. This is my HTML: <div c ...

Comparing .innerHTML with createElement() | Exploring setAttribute() versus the Direct method*

Someone mentioned that this approach was not considered "proper", but I didn't pay much attention to it until I encountered a run-time error in IE9. Now, I need help converting the code to utilize object properties instead. What is the reason behind i ...

Dealing with errors in node.js

Node.js asynchronous functions typically have a callback, with some like fs.writeFile passing an err argument. fs.writeFile('message.txt', 'Hello Node', function (err) { if (err) throw err; console.log('It\'s saved!& ...

Expanding SVG width upon import through Icomoon

After exporting an SVG file from Illustrator (already "Fit to selected Art"), I encountered an error while importing it via the Icomoon App. Strangely, other SVGs are importing correctly. I would appreciate any help or insight you can provide. Thank you i ...

Changing div height with scrolling

I am looking to dynamically increase the height of a div as the user scrolls through the page. You can see the site I am working on here: The specific div that needs its height adjusted is the menu located on the right side of the page. I have developed ...

Which option offers superior performance: using attributes through HTML or jQuery?

At times, I find myself needing to include special classes, divs, and attributes in my HTML code for jQuery scripts to function properly (the site's "no-JavaScript" version doesn't require these elements). You probably understand what I mean. I& ...

Nextjs has a tendency to transform my personalized components into div elements

Why do my components (ElementTile) on my page change into divs when viewed in the browser? The CSS rules that apply to "ElementTile" also do not work, which is expected because they are converted to divs. Is there a way to change this behavior? Thanks in ...

Having trouble with the animate() function not working properly?

I have been working on the following code snippet: var isOn = false; $('.switch').on("click",function(){ if (isOn){ $('.toggle').animate({ left:"18px" },10,"linear", { complete: function(){ $(&ap ...

Arrange the file names in either ascending or descending order

I've come across another query. My text files are stored in the local document folder. I managed to showcase the file names in ascending order. However, I'm curious about how to sort them in descending order using PHP. Your guidance is much appre ...

What is the method to retrieve the string value from a JavaScript String object?

Is there a way to extend a method to the String prototype and manipulate the string value? I'm facing some difficulty in accessing the actual string value, as this, the current object context, seems to refer to the string object instead. String.pro ...

Tips for creating a synchronous jQuery "$.post" request

After much research and effort, I have finally come to the last item on my bug fix list. This one involves creating a function that will return true or false to indicate whether the validation was successful. My approach involves using ajax to compare cer ...

Is it possible for nextAll() to exclude a specific parent element and search only for children inside that parent?

Below is the structure of my html ajax form: <form name="vafForm" id="vafForm" method="GET" action="urlfor ajax"> <input type="hidden" value="0" id="vafProduct"> <select class="catSelect {prevLevelsIncluding: 'cat'} c ...

Creating a unique look for unordered list items in a dropdown navigation

I'm currently working on creating a drop-down menu using nested unordered lists. The functionality of the menu is all set, but I'm running into some styling issues. The main link that triggers the drop-down should have a blue background with whit ...

Displaying geoJSON data from a variable instead of a file is a feature implemented by

Let's say I have a geoJSON data stored in a variable or parsed as an object: // GeoJSON stored as an object var segment = segment; // GeoJSON saved as a JSON string var json = JSON.stringify(segment); Now, the challenge is to display this geoJSON o ...

Encountering a PDF loading error when integrating ReactPDF in a React project

Having trouble trying to display a PDF file using the PdfReact component. Every time I attempt to load the PDF, I encounter the following error: Warning: Ignoring invalid character "114" in hex strinpdf.worker.js:342 Warning: Ignoring invalid character " ...