Expanding divs automatically depending on the content they contain

Currently, I have been developing a template for a database-driven page that is supposed to contain four divs for content arranged like this:

----- -----
| 1 | | 2 |
----- -----
----- -----
| 3 | | 4 |
----- -----

The information in each box will always remain the same. For example, news will always be in box #1 and images in box #2. Depending on the available content, there could be all four sections displayed or only one. In cases where a box is missing, such as box 2, I am looking for a way to make box 1 expand to fill the width of the parent div.

For instance:

-----------
| 1       |
-----------
----- -----
| 3 | | 4 |
----- -----

or if boxes 3 & 4 do not exist:

-----------
| 1       |
-----------
-----------
| 2       |
-----------

It seems like achieving this might require conditional statements, but I am curious if there is a CSS or jQuery solution. It should be a simple task, but I am struggling to figure it out.

I tried setting up two floating divs with 50% width side by side, but I am unsure how to handle expansion when one of them is missing.

Thank you!

Edit: Including HTML! Nothing too complex here...

    <div class="auth-secondary">

    <div class="auth-upcoming auth-3d">
        <span class="auth-h3">Upcoming Events</span>
        <p>
            <strong>March 5, 2014</strong><br>
            Book signing
        </p>
        <p>
            <strong>March 5, 2014</strong><br>
            Ice cream party
        </p>
    </div><!-- end auth-upcoming -->

    <div class="auth-media auth-3d">
        <span class="auth-h3">Media Gallery</span>
            <p>
                <img src="http://placehold.it/74x74"> &nbsp; 
                <img src="http://placehold.it/74x74"> &nbsp;
                <img src="http://placehold.it/74x74"> &nbsp; 
                <img src="http://placehold.it/74x74"> &nbsp;
            </p>
    </div>
</div> <!-- end auth-secondary-->

Answer №1

If you prefer not to have a div in the DOM, here is a solution using only CSS.

In your HTML file, include a "wrapping" div for each row:

<div class="row">
    <div>1</div>
    <div>2</div>
</div>
<div class="row">
    <div>3</div>
    <div>4</div>
</div>

Apply this CSS as well:

.row {
    width: 600px;
    display: table;
}
.row > div {
    display: table-cell;
}

By doing so, you will achieve this visual result.

If div #3 and #4 are absent and you want div#2 on a new line, you may need to modify your script server-side by adding additional classes or elements.

I hope this solution proves helpful to you!

Answer №2

Check out this alternative option that may not be pure CSS, but could still suit your needs depending on the requirements.

Have you considered how the children are being inserted into their parent container?

The approach here involves adding a .half class to the child element, which essentially splits its width in half. Understanding the context of your question is crucial in achieving the desired outcome.

Feel free to experiment with the following demonstration:

CSS:

body * {
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
}

.parent {
    width: 600px;
    height: 300px;
    border: 5px solid #ffdd00;
    margin-bottom: 20px;
    padding: 5px;
}

.child {
    width: 100%;
    height: 100%;
    background: #ff7200;
}

.child.half {
    width: 49.5%;
    display: inline-block;
    vertical-align: top;
}

jQuery:

var child = '<div class="child">I am a child DIV</div>',
    halfChild = '<div class="child half">I am a child DIV</div>'

$('#fullTwo').on('click', function() {
    if($('.parent').find('.child')) {
        $('.parent').append(halfChild);
        $('.parent').find('.child').addClass('half');
    }
    else {
        $('.parent').append(child);
    }
});

For a practical demonstration, view the fiddle linked here: Demo

Alternatively, explore another example showcasing how introducing an additional class can impact the layout: Demo

Answer №3

Let's imagine a scenario where news, images, comments, and advertising elements are arranged in your HTML like this:


-------------------
|  News   | Images |
|------------------
| Comments| Advertising|
-------------------

One approach could be to always have a set base HTML structure and dynamically adjust the width of each element based on its content:

<div class="news"></div>
<div class="images"></div>
<div class="comments"></div>
<div class="advertising"></div>

Your JavaScript code would then look something like this:


var isNewsEmpty = $('.news').html() == "";
var isImagesEmpty = $('.images').html() == "";
var isCommentsEmpty = $('.comments').html() == "";
var isAdvertisingEmpty = $('.advertising').html() == "";

// Adjust width if empty
if (isNewsEmpty) { $('.images').css('width','100%') }
if (isImagesEmpty) { $('.news').css('width','100%') }
if (isCommentsEmpty) { $('.advertising').css('width','100%') }
if (isAdvertisingEmpty) { $('.comments').css('width','100%') }

I hope this explanation proves helpful!

Update

This method will still work even if one of the sections is missing.

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

What causes an "Undefined index" error in jQuery when making AJAX requests?

Whenever I make an AJAX request in my main.js file, I encounter the following error message: Undefined index: id in sqlinfo.php on line 13 I am puzzled because I believe that I am populating the request object correctly. What's even more perplexing i ...

Ways to optimize view caching to prevent unnecessary file reads and rendering

My current code includes multiple view render calls: router.get('/mcn', (req, res) => { res.render('product/mcn', { layout: 'product/layout', contactKey: 'mcn' }); }); router.get('/agency', (req, res ...

Unusual issue with jQuery function failing to detect click events

As I delve into my first jQuery function, the primary goal is to assign a form to the function. Upon clicking the submit button, it should perform validation on each :input field within the function. The form is set as the selector for the function: $("f ...

Step-by-step guide for setting up CodeMirror

I'm feeling a bit lost with what to do next: <link rel="stylesheet" href="lib/codemirror.css"> <script src="lib/codemirror.js"></script> <script> var editor = CodeMirror.fromTextArea(myTextarea, { mode: "text/html" }); ...

Setting up the CSS loader in a Vue.js project using webpack

I am currently working on a new vue-cli project and have successfully installed the Pure.CSS framework using npm install purecss --save. However, I am struggling to seamlessly integrate, import, or load the css framework into my project. I am unsure of whe ...

How to Resubmit a Form Using Ajax?

My form utilizes ajax to call the server for user authentication. However, I've encountered an issue where if a user enters the wrong password and then tries to correct it, any subsequent calls do not trigger the on('submit') function, leavi ...

Loading an empty CSS file in Node.js

Just starting out with node.js, and I could really use some help with a small css and image issue that I'm facing. I've streamlined my html and .js for clarity. Despite trying everything, the css and image just won't load. My form and server ...

Troubleshooting: PHP Integration Issue with HTML Document

I have a simple HTML file displaying text and including a PHP file with basic echos: The HTML code is in 'home.html' file: <html> <body> <h1>Welcome to my home page!</h1> <p>Some text.</p> <p>Some more ...

I have an HTML table with multiple cells containing inner HTML tables. I have implemented a function along with buttons to filter the main table, excluding the inner tables

My HTML Table is generated from my database, containing information about machines and their status pulled from emails with HTML Tables. Each row has a click option to open/hide the <td> tag showing the original table for more details and better trac ...

Transform jQuery scroll script into vanilla JavaScript

While I am quite familiar with jQuery, I find myself struggling when it comes to using pure JavaScript. Could anyone provide guidance on how I can convert my jQuery code into vanilla JavaScript? Your help is greatly appreciated! Below is the code that I ...

No results found for the xpath within the <p> tag

I'm currently using selenium.webdriver chrome to scrape data from my website, and I need to extract the location details of visitors. Although I have successfully identified the <p> tag that contains 'location', it is returning None. ...

Troubleshooting CSS3 @keyframes animation issues within Firefox's shadow DOM

I am currently working on creating a custom shimmer loader using CSS3 keyframes animation within the shadow DOM. While the shimmer effect displays perfectly in Chrome and Safari, it seems to be malfunctioning in Firefox. Below is a concise snippet that de ...

What is the best way to convert every database field into a public variable in PHP?

After running the query below, I have retrieved all database fields: "SHOW COLUMNS FROM admin" Now I am curious about how to convert each field into a public variable within a class structure since I am working with object-oriented PHP. My first step i ...

Customize jqGrid Paging Input Size

Can the size of pginput in jqGrid be changed? By default, it appears like this: <input class="ui-pg-input" type="text" role="textbox" value="0" maxlength="7" size="2"> If no direct way is available, I solved it using the following code snippet: $( ...

The variables are filled with HTML tags that will render the display in

I am facing an issue with displaying HTML tags in my website. When I try to print a variable containing HTML tags in the tpl file, it shows the tags along with the content. This is how it looks in the PHP file: $content = "<h1>Header</h1>< ...

The form refuses to submit using ajax, although it typically submits without any issues

Check out this code snippet: $('.saveCheck').on('click',function() { var form = $(this).parents('form'); form.submit(function (event) { $.ajax ({ t ...

JQuery form plugin - submitting a form automatically on onchange event

As a beginner in JQuery, I am looking to utilize the JQuery form plugin for file uploads and would like to trigger the form submission as soon as a file is selected. This should occur upon the onchange event of the input tag: myfile. <html> <body ...

Safari re-downloads background image when revisiting with jQuery CSS

Using jQuery to set a background-image on my website: $('.header-image').css('background-image', 'url(/img/image.jpg)'); However, upon returning to the page from Safari, the image is downloaded again, unlike Chrome and F ...

What is the best method to calculate the dimensions of flex items without relying on percentages?

Imagine this as the structure of my HTML, with an unspecified number of div elements: <body> <div></div> <div></div> <div></div> <div></div> <div></div> <div>& ...