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

Ways to modify the appearance of the button within ion-calendar

Looking to customize the styling of ion-calendar classes Attempting to add styles to the ion-calendar-month class, but not seeing any changes take effect. ...

How can I ensure a header is displayed on each page by utilizing CSS or JavaScript/jQuery?

On a lengthy page with approximately 15 pages of text, I would like to insert a header at the beginning of each page when the document is printed by the user. Can this functionality be achieved using CSS or JavaScript/jQuery? ...

Is it possible to call a REST API in Javascript by passing the username and password as

I have been attempting to use Javascript to call the AwaazDe REST API with a specific username and password, but I'm encountering issues. Below is my code: function authenticateUser(user, password) { var token = user + ":" + password; ...

Aligning the column to the right to ensure the text is centered horizontally on the screen

<div className={css.title} > <div className={css.row}> <div className={css.columnLeft}> <div className={css.header}>Images</div> </div> <div className={css.col ...

How to Conceal File Extensions with .htaccess

Can anyone provide guidance on the best way to hide .php extensions using HTAccess, even for sub-folders? I have attempted various solutions from previous answers but none seem to work. ...

Issues arise when the sub-menu does not function properly and overlaps with other elements of

I've been working with a client on their website and encountered an issue. On the mobile version of our menu, when I hover over a menu item that has several sub-menu items, those items display properly, but there is an element below them showing thro ...

Save the contents of a file within an HTML table using jQuery

I needed to insert multiple files into the database by uploading and adding each file's content to a table. Once all files were added to the table, I included the table's values along with the file content in form data which was then passed to aj ...

When attempting to send JSON data using Ajax, you may encounter an issue such as receiving an error message

I am currently working on developing a login with Facebook application using Codeigniter. My challenge is passing JSON data to my controller through AJAX. This is the code snippet I am using: var data = JSON.stringify(response); alert(data); $.ajax ...

Exploring the differences between Material-UI's makeStyles and withStyles when it comes to

One thing I've observed is that the naming convention for classes created with makeStyles and hooks looks like this: https://i.stack.imgur.com/HcDUc.jpg On the other hand, classes produced using withStyles and higher order components (HOC) follow a ...

Altering the appearance of a component that is currently selected and in use

Currently, I have incorporated a component with its selector within another component as shown below: <div class="col-xl-4" style="margin-bottom: 30px;"> <app-patient-info-accordion *ngIf="patient" [cardTitle]=&qu ...

Utilizing jQuery for resizing images

I'm encountering an issue with my Jquery code as I work on creating a gallery feature. My goal is to have the selected image appear in the center of the screen when clicked, resized to fit the screen size if necessary. However, I've run into perf ...

I am currently facing an issue with retrieving the class value that is being generated by PHP code

I am currently facing an issue with jQuery and PHP. Whenever I attempt to target the click event on the class ".id_annonce" in the dynamically generated PHP code, it doesn't retrieve the exact value of what I clicked. Instead, it always gives me a fi ...

I require the variable to be accessible from all corners

Is there a way to access the variable "finalPrice" in a different function? I'm trying to achieve this and could use some guidance. function available(id){ $.ajax({ method:"GET", }).done(function(data){ for( ...

Change the JavaFX ToggleButton's color and revert back to its original color

Can you tell me what the default background and border color is for a toggle button? Here’s an example of code that changes the background color of a toggle button: i.toggle11.setOnAction(e->{ if(i.toggle11.isSelected()){ i.toggle ...

Retrieving specific value from a Parent Controller in AngularJS using UI Router

I have a request to display the value stored in $scope.resAVal on my index.html page. This value is accessible within the RootCtrl. index.html <!DOCTYPE html> <html ng-app="plunker"> <head> <!-- any required JavaScript librarie ...

Displaying database values in an array within an HTML format

I need help displaying database values by replacing the $view['time'] with %time% using an array. For example, if $view['time']='8:00 pm';, then when I write %time% it should display 8:00 pm. It works for a single row, but w ...

The concept of CSS inheritance within div elements

I've been researching extensively about the concept of CSS inheritance, but I have come across a puzzling question that remains unanswered. Consider the code snippet below: <!DOCTYPE HTML> <html> <head> <style type="text/css"> ...

What is the method to retrieve the return value from this ajax request?

Here's a code snippet: var information = { ObtainInfo : function() { var url = 'http://www.bungie.net/api/reach/reachapijson.svc/game/info/'+storage.get('apikey'); $.ajax({ url: url, su ...

Transfer data between an HTML page and a PHP page hosted on separate locations using jQuery

Below is the code snippet I am currently working on: function send_data() { var a=$("#username").val(); var b=$("#password").val(); $.post("http://localhost/login/login.php", {uname: a, pswd: b}, function(data) { $("#result").html(data); }); ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...