What is the best way to allow a container div to only show horizontal overflow, without relying on "display:inline-block" for its inner divs?

My coding challenge involves dynamically creating nested <div> elements within another <div> when a button is clicked. Upon clicking the button, a new inner <div> with a unique id is generated inside the outer <div>, each possessing a random CSS margin-top value. Although this functionality is functional, my goal now is to constrain the scrolling of the outer <div> to horizontal movements only. To achieve this, all inner <div> elements need to be created inline. Unfortunately, using display:inline-block for the inner <div> blocks impedes the random margin-top feature.

(Kudos to user totymedli for the coding assistance)

HTML

<button id="button1">Add box</button>
<div id="outer"></div>

CSS

#outer {
position:absolute;
white-space:nowrap;
height:118px;
overflow:auto;
width:100%;
padding:2px;
}

.box{
float:left;
width:48px;
height:48px;
background-color:#000;
margin-left:5px;
}

Javascript

var number = 0;

document.getElementById("button1").addEventListener("click", pressButton, false);

function pressButton() {
    ++number;
    makeDiv(number);
};

function makeDiv(x) {
    var innerDiv = document.createElement("div");
    outer.appendChild(innerDiv);
    innerDiv.className += " box";
    innerDiv.setAttribute("id", "innerDiv" + x);
    innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
}; 

Test out the live Demo.

In the demo, you'll observe that the creation of new inner <div> elements is functioning smoothly with varying margin-top values. How can I enforce horizontal scrolling on the outer <div> while preventing the inner <div> from wrapping onto the next line?

Answer №1

Definitely, the trick here is to utilize display: inline-block along with vertical-align: top for the desired outcome.

LATEST DEMO

One key point to remember is that if you don't specify a value for vertical-align, it defaults to baseline, which may cause confusion when setting margins.

.box{
    display:inline-block;
    vertical-align:top;
    width:48px;
    height:48px;
    background-color:#000;
    margin-left:5px;
}

If, for some reason, floating elements is your preference (although not recommended), ensure the width of the parent element can accommodate the child elements accordingly.

Answer №2

Check out this suggested code:

If you don't want to use inline-block, consider using inline-table instead.

Fiddle link

.box{
    display: inline-table;
    vertical-align: top;
    width: 48px;
    height: 48px;
    background-color: #000;
    margin-left: 5px;
}

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

Elevate Your Flipclock.js

I am currently working on a website that utilizes flipclock.js, but I am facing some challenges in enlarging it to occupy more space on the page. Is there anyone who knows how to upscale or increase its size? ...

Building a TTL based schema in NestJs with MongooseIn this guide, we will explore

In my NestJs(TypeScript) project, I am attempting to create a self-destructing schema using the mangoose and @nestjs/mongoose libraries. Unfortunately, I have been unable to find a clear way to implement this feature. While I know how to do it in an expres ...

Is there a way to verify file types using Vuelidate?

Is there a way to validate file types like png, jpg, and jpeg using Vue.js's Vuelidate library? ...

Tips for utilizing the font-family style to span multiple columns

I recently discovered that you can set the background color across table columns using the <colgroup> tag. table { border: 2px solid; border-collapse: collapse; } td { border: 2px solid; } <ta ...

Is it possible to send a PHP variable to a popup using a button and JavaScript?

I am facing an issue with a dynamically created table in PHP that displays requests. Each row in the table has a button to open a popup. I need to pass the ID of each request to the popup to retrieve all the data associated with it. Can someone guide me o ...

Troubleshooting Issues with Uploading Images to Firebase Storage Using ReactJS, JavaScript, and Firebase

Despite watching countless tutorials and conducting thorough research, I continue to encounter errors in my code. One recurring error can be seen in the image below: https://i.sstatic.net/AmG5D.png In one file, I include the line import firebase from &apo ...

The navigation bar is not showing up at the top of my webpage as expected, instead, it is displaying

1 I attempted to build a model Google site to enhance my HTML and CSS skills, but I encountered an unusual issue where my navigation menu is showing up inside my image div, even though it was created before that. I have given backgrounds to the navs and i ...

Having trouble scrolling on a Chrome browser with the Muse website?

My significant other is having some trouble with her muse-created website at . It seems to have an issue scrolling horizontally on Chrome, but works fine on Safari and Edge. The site is part of a university project and she hopes it will eventually look lik ...

Parsing all HTML elements using Nokogiri

I've been searching everywhere and all I could find was how to use CSS selection with Nokogiri. What I really need is to completely remove all HTML tags. For instance, this: <html> <head><title>My webpage</title></head& ...

Tips for effectively interpreting a json string

Trying to extract specific fields from a JSON string and display them on an HTML page, but encountering the following error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data This is the JSON being sent: { "Order0& ...

Leveraging $http and $q in an Angular configuration with a service/provider

My goal is to load specific configurations for each controller in the app.config section. Each controller requires a distinct set of data, but these sets are not mutually exclusive. I am struggling to find a solution to this issue. .config(['$routePr ...

Unveiling the Truth about Svelte Transitions

Recently, I attempted to incorporate the guidance provided in this repl () for implementing flying and fading effects on divs. However, it seems that I may have a slight misunderstanding regarding the concept... To tackle this, I designed a component rese ...

Using RTK Query to store data in a Firebase Realtime Database

Currently, I am facing an issue while trying to retrieve data from a Firebase Realtime Database using RTK Query. The code in this section is throwing an error because the return value is incorrect. If anyone has experience with this particular issue, I wou ...

What is the best way to give a fixed height to Card content in Material UI? Is CSS the way to go?

I've been struggling with a design issue involving Material-UI cards used to display News. The problem arises when the paragraph section of the card occupies multiple lines of text. When it spans two lines, there is a 10px spacing between the paragrap ...

Would it be better to lock a variable stored in req.session, or opt for a massive global variable instead?

As I delve into creating a game using node.js, the premise is sending units on missions and waiting for their return. The challenge lies in ensuring that the same unit cannot be sent on two different missions simultaneously, nor can two sets of units be di ...

Steps for including a font ttf file in Next.js

As a newcomer to Nextjs, I am eager to incorporate my own custom fonts into my project. However, I find myself completely bewildered on how to execute this task (my fonts can be found in the "public/fonts/" directory). The contents of my global.css file ar ...

Unable to retrieve accurate information

I am currently in the process of developing an application that utilizes Spring Boot and ReactJS. I encounter an issue where, despite entering correct data values in the form on the client side using the POST method, the response displays NULL values. Upo ...

Codepen fails to function properly after being uploaded to a server

I have encountered an issue with my code on CodePen. After exporting it as a .zip file and attempting to run it on a local server, it failed to work. I am unsure of the exact reason behind this. I made sure to include all the necessary dependencies in the ...

Is it possible to incorporate a foreach loop while also implementing unique adjustments at specific locations within the code?

I have been searching for a solution to this problem on various forums, but I couldn't find one that fits my needs. My challenge is to create a foreach loop for 12 elements, with 3 of them having a different class applied to them. This is the code I ...

Firebug detected an error with the regular expression flag "h" after executing the YUI Compressor

When I run YUI Compressor, an error occurs with the message: invalid regular expression flag h [Break On This Error] ction(event){$(this).removeClass('lumi...cs_glb.php</b> on line <b>221</b><br/> The issue seems to be with t ...