Adding additional elements to a div in a horizontal orientation

I am currently working on a project where I need to display bars and restaurants based on specific filter criteria. I have a container div called .resultsContainer where all the results will be displayed. While I can easily append more divs (.barContainer) to this container, I am facing challenges when it comes to appending information to these divs. My goal is to have each .barContainer (.infoContainer) hold details such as pictures, names, and addresses horizontally without any margins in between them. However, no matter how hard I try, the divs are stacked vertically due to the full width taken up by margins even when set to zero. I attempted to use createDocumentFragment() function to stack child elements together before appending them to .barContainer, but the layout still isn't as desired. I believe there might be a way to dynamically create an HTML template for displaying the information, but being new to web coding, I'm struggling to find the right solution. In my code, I intend to include picture, address, and name in the infoContainer wherein each of them should occupy one third of the parent div's width and be displayed next to each other seamlessly without any spacing. Moreover, they should have different background colors for distinction.

HTML:

<body>
    <button type="button" id="myBtn" onclick="appendBars()">Append</button>     
    <div id="resultsContainer"></div>
</body>

JS:

function appendBars(){

    var barContainer = document.createElement("div");
    barContainer.className = "barContainer"

    var infoContainer = document.createElement("div");
    infoContainer.className = "infoContainer";

    var barPicture = document.createElement("div");
    barPicture.className = "barPicture";

    var barName = document.createElement("div");
    barName.className = "barName";

    var barAddress = document.createElement("div");
    barAddress.className = "barAddress";

    var fragment = document.createDocumentFragment();

    fragment.appendChild(barPicture);
    fragment.appendChild(barName);
    fragment.appendChild(barAddress);
    infoContainer.appendChild(fragment);

    barContainer.appendChild(infoContainer);

    document.getElementById("resultsContainer").appendChild(barContainer);

}

CSS:

#resultsContainer{
    float: right;
    background: red;
    width: 620px;
    height: 100%;
    overflow-x: auto;
}

.barContainer {
    background-color: white;
    width: 100%;
    height: 200px;
    border-top: 0px;
    border-right: 0px;
    border-bottom: 1px;
    border-style: solid;
    border-color: grey;
}


.infoContainer{
    width: 620px;
    height: 180px;
    background-color: white;
    padding: 10px;
}

.barPicture{
    width: 200px;
    height: 180px;
    margin: 0;
    background-color: yellow;
}

.barName{
    background-color: blue;
    margin: 0px;
    width: 200px;
    height: 180px;
}

.barAddress{
    background-color: green;
    margin: 0px;
    width: 200px;
    height: 180px;
}

Answer №1

To ensure that your elements only take up the necessary space, consider setting them to inline-block. By default, a div element is block-level and will always occupy the entire row regardless of the specified width.

If you want to learn more about the differences between block and inline elements, check out this resource.

function appendBars(){

    var barContainer = document.createElement("div");
    barContainer.className = "barContainer"

    var infoContainer = document.createElement("div");
    infoContainer.className = "infoContainer";

    var barPicture = document.createElement("div");
    barPicture.className = "barPicture";

    var barName = document.createElement("div");
    barName.className = "barName";

    var barAddress = document.createElement("div");
    barAddress.className = "barAddress";

    var fragment = document.createDocumentFragment();

    fragment.appendChild(barPicture);
    fragment.appendChild(barName);
    fragment.appendChild(barAddress);
    infoContainer.appendChild(fragment);

    barContainer.appendChild(infoContainer);

    document.getElementById("resultsContainer").appendChild(barContainer);

}
#resultsContainer{
    float: right;
    background: red;
    width: 620px;
    height: 100%;
    overflow-x: auto;
}

.barContainer {
    background-color: white;
    width: 100%;
    height: 200px;
    border-top: 0px;
    border-right: 0px;
    border-bottom: 1px;
    border-style: solid;
    border-color: grey;
}


.infoContainer{
    width: 620px;
    height: 180px;
    background-color: white;
    padding: 10px;
}

.barPicture{
    width: 200px;
    height: 180px;
    margin: 0;
    background-color: yellow;
    display:inline-block
}

.barName{
    background-color: blue;
    margin: 0px;
    width: 200px;
    height: 180px;
    display:inline-block
}

.barAddress{
    background-color: green;
    margin: 0px;
    width: 200px;
    height: 180px;
    display:inline-block
}
<button type="button" id="myBtn" onclick="appendBars()">Append</button>     
    <div id="resultsContainer"></div>

Answer №2

To optimize the layout of your divs, you can utilize the display: flex property on the .infoContainer class. This will ensure that the div elements are aligned in a row. Additionally, consider using display: inline-block; for the .barPicture and .barName classes, although be cautious as it may lead to overflow-related issues.

Experiment with .infoContainer {display: flex;}:

function appendBars(){

    var barContainer = document.createElement("div");
    barContainer.className = "barContainer"

    var infoContainer = document.createElement("div");
    infoContainer.className = "infoContainer";

    var barPicture = document.createElement("div");
    barPicture.className = "barPicture";

    var barName = document.createElement("div");
    barName.className = "barName";

    var barAddress = document.createTextNode("div");
    barAddress.className = "barAddress";

    var fragment = document.createDocumentFragment();

    fragment.appendChild(barPicture);
    fragment.appendChild(barName);
    fragment.appendChild(barAddress);
    infoContainer.appendChild(fragment);

    barContainer.appendChild(infoContainer);

    document.getElementById("resultsContainer").appendChild(barContainer);

}
#resultsContainer{
    float: right;
    background: red;
    width: 620px;
    height: 100%;
    overflow-x: auto;
}

.barContainer {
    background-color: white;
    width: 100%;
    height: 200px;
    border-top: 0px;
    border-right: 0px;
    border-bottom: 1px;
    border-style: solid;
    border-color: grey;
}


.infoContainer{
    width: 620px;
    height: 180px;
    background-color: white;
    padding: 10px;
    display: flex;
}

.barPicture{
    width: 200px;
    height: 180px;
    margin: 0;
    background-color: yellow;
}

.barName{
    background-color: blue;
    margin: 0px;
    width: 200px;
    height: 180px;
}

.barAddress{
    background-color: green;
    margin: 0px;
    width: 200px;
    height: 180px;
}
<button type="button" id="myBtn" onclick="appendBars()">Append</button>     
    <div id="resultsContainer"></div>

Answer №3

It seems like you're asking about how to style certain elements in CSS. To achieve this, simply add the following code snippet to your stylesheet:

/* TARGETED CLASSES FOR STYLING */
.barPicture,
.barName,
.barAddress {
    display: inline-block;
}

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

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Error encountered: Vue.js encountered an unexpected token, which is 'export'

Having an issue with Google location autocomplete, specifically this error: SyntaxError Unexpected token 'export' Here is the link to the functional code: https://codesandbox.io/s/nifty-bardeen-5eock ...

Issue with Ionic 2's infinite scroll not triggering method on second scroll attempt

I utilized the ion-tab element to showcase a page (inboxitem) which encompasses ion-list and makes use of ion-infinite-scroll. The following code snippet resides in inboxitem.html <ion-content class="inbox can-swipe-list"> <ion-list> ...

Creating a single Vuetify expansion panel: A step-by-step guide

Is there a way to modify the Vuetify expansion panel so that only one panel can be open at a time? Currently, all panels can be closed which is causing issues. I would like the last opened panel to remain open. I also want to prevent closing the currently ...

Inquire regarding the header image. Can you confirm if the current HTML and CSS for this is the most efficient approach?

This is a preview of my website in progress (Disclaimer: I'm currently learning HTML to build this site, design comes next. I know it's not the conventional way to design a site, but oh well) Check out the site here Is the HTML code for the hea ...

Getting request parameters within Model in Loopback can be done by accessing the `ctx`

common/models/event.json { "name": "Event", "mongodb": { "collection": "event" }, "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "http": { "path": "organizer/:organizer_id/events" }, "properties": {}, "va ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...

The AJAX request was a success, but unfortunately there is no usable data available

After submitting the registration form, jQuery sends the data to register.php, which then responds with JSON data for jQuery to process. Everything seems to be functioning correctly as users are successfully registered. The network response tab shows that ...

Vuetify vueJS dialog with elevated design

Is there a way to completely remove the elevation of a v-dialog so that it has no shadow at all? The elevation property in the v-dialog itself and using the class as Class = "elevation-0" have not worked for me. Here is the link to the component ...

Elements of <nav> within a <footer> section

I've recently started using HTML5 display elements like header, footer, and nav. While reading about the nav element in particular, I found this interesting information in the HTML5 spec: The nav element is primarily intended for major navigation b ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

When the file is active on a local machine, the bot commands run smoothly. However, these commands do not execute on a remote

Lately, while working on coding a discord bot using discord.js, I came across an issue. Whenever I run my bot on my local machine, all the commands work perfectly fine. However, after committing and pushing the code to GitHub, and then allowing buddy.works ...

Expanding the text box in PHP to incorporate new lines

So I have an HTML form where users enter addresses in a text box. The PHP code that processes this input looks like this: $address = $_POST["address"]; echo $address; The output currently comes out as one long line, for example: The Manager, Scotia b ...

Struggling to keep my image buttons aligned in a horizontal line at the center, but they keep stacking vertically instead

I'm struggling to keep a row of image buttons centered horizontally, regardless of the window size. However, when I manage to center the buttons, they end up stacking vertically instead of aligning in a single line. I've experimented with differ ...

Iterate over various selection lists and tally the frequency of each option being chosen

I am currently working on a website that requires multiple instances of the same select-option to be created. I want to keep track of how many times each option is selected, and save that count as a variable to be used in a PHP email function. For instanc ...

Enhance your application by utilizing additional hooks in the Context API

I'm exploring API and react hooks and have a query related to dispatching API fetch to ContextAPI component. Is there a way to consolidate all useState hooks into a single ContextAPI component? The objective is code refactoring by breaking it down int ...

Convert JSON data from jQuery into a modal form within a div element

I am currently working on an MVC application and attempting to populate a bootstrap modal form with data from the server. My approach involves: 1) Loading a grid with various IDs, each linked to a javascript onclick function. 2) The function retrieves th ...

Labels are overlapping each other and being aligned to the right side

Working with the most up-to-date version of Bootstrap, I am currently designing a search bar featuring a dropdown menu preceding the search button. Upon clicking the dropdown, various controls are revealed. Below is the HTML code for this configuration: ...