A div element that automatically adjusts its width to fill the available horizontal space, and is then re

div elements next to each other horizontally. The right div should adjust its size based on its content up to a set maximum width, while the left one should occupy the remaining space. I have successfully achieved this layout by floating the right div to the right and setting the overflow of the left div to hidden. In the HTML code snippet provided, you can see how these div elements are structured within a parent div. The CSS styles applied ensure that the right div adjusts its width dynamically while respecting the max-width constraint when floated to the right. The challenge arises when viewing the page on a small screen or browser window, as I wish for the div elements to be stacked vertically instead of horizontally. Although I attempted a simple media query to address this, it caused the right div to appear above the left div in the smaller layout. To resolve this issue, I explored alternative methods such as using display: table and table-cell properties instead of floating. However, these attempts failed to maintain the dynamic sizing of the right column while enforcing a max-width limit. If you would like to view a working example and toggle between the small and large layouts, please refer to the JSFiddle link provided.

Answer №1

The solution provided in a Stack Overflow thread suggests using Flexbox instead of jQuery, especially if you only need compatibility with one modern browser like Mobile Safari. Additionally, check out the height issue in IE concerning the left box in this Fiddle example.

Here is the recommended fiddle: Link to Fiddle

For dynamic adjustment of the right div, refer to this alternative demonstration.

CSS:

.frame {
    position:relative;
    background-color: lightgreen;
    width: 80%;
    padding: 12px;
    overflow:hidden;
    flex-flow:row wrap;

    -webkit-justify-content: flex;
    -moz-justify-content: -moz-flex;
    justify-content: flex;

    display: -webkit-box; /* Safari */ 
    display: -moz-box; /* Firefox 21- */
    display: -ms-flexbox; /* IE 10+ */
    display: -webkit-flex; /* Chrome */
    display: flex; /* Standard (Firefox 22+) */

    -webkit-box-orient: horizontal;
    -moz-box-orient: horizontal;
    -webkit-box-direction: normal;
    -moz-box-direction: normal;
    -ms-flex-direction: row;
    -webkit-flex-direction: row;
    flex-direction: row;
}

.left {    
    -ms-flex-order: 1;     
    -webkit-order: 1;
    order:1;

    -webkit-box-flex: 2;      /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 2;         /* OLD - Firefox 19- */
    -webkit-flex: 2;          /* Chrome */
    -ms-flex: 2;              /* IE 10 */
    flex: 2;                  /* NEW, Spec - Opera 12.1, Firefox 20+ */

    background-color: #709670;
    border: 1px solid black;
    width: auto;
}

.right {    
    -ms-flex-order: 2;
    -webkit-order: 2;
    order:2;

    -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1;         /* OLD - Firefox 19- */
    -webkit-flex: 1;          /* Chrome */
    -ms-flex: 1;              /* IE 10 */
    flex: 1;                  /* NEW, Spec - Opera 12.1, Firefox 20+ */

    background-color: #127212;
    color: white;
    border: 1px solid black;
    width: auto;

    -webkit-box-ordinal-group: 2;   /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-ordinal-group: 2;      /* OLD - Firefox 19- */
    -ms-flex-order: 2;              /* TWEENER - IE 10 */
    -webkit-order: 2;               /* NEW - Chrome */
    order: 2;                       /* NEW, Spec - Opera 12.1, Firefox 20+ */
}

@media screen and (max-width: 700px) {
    .frame {
        -webkit-box-orient: vertical;
        -moz-box-orient: vertical;
        -webkit-box-direction: normal;
        -moz-box-direction: normal;
        box-orient: vertical;
        -ms-flex-direction: column;
        -webkit-flex-direction: column;
        flex-direction: column;
    }
}

I am thrilled with the outcome and confident that you will be too! It offers almost full support across browsers, with the exception of Mobile Safari.

Answer №2

An Innovative Styling Technique Using CSS and jQuery

Imagine a scenario where the HTML structure can be modified to have the .left element come before the .right element:

<div class="frame">
    <div class="left">Lorem ipsum dolor sit amet, c...</div>
    <div class="right">
        <div class="color-wrap">I adjust my width ...</div>
    </div>
</div>

For wide screens, consider applying the following CSS rules:

.frame {
    background-color: lightgreen;
    width: 80%;
    padding: 12px;
    overflow: auto;
}
.left {
    background-color: #709670;
    border: 1px solid black;
    display: table-cell;
}
.left .color-wrap {
}
.right {
    display: table-cell;
    width: 200px;
    vertical-align: top;
}
.right .color-wrap {
    background-color: #127212;
    color: white;
    border: 1px solid black;
    display: inline-block;
}

For smaller screens, utilize media queries as shown below:

@media screen and (max-width: 700px) {
    .left {
        display: block;
    }
    .right {
        display: block;
        width: auto;
    }
    .right .color-wrap {
        display: block;
        width: auto;
        color: yellow;
    }
}

To address cases where the .right element contains only a single line of text, you can use either fixed widths or a combination of max-width and min-width within a table-cell layout.

If you wish to apply a background color specifically to the text portion, employ a wrapper element such as .color-wrap for targeted styling.

Another consideration is adjusting the width of the .right element dynamically using jQuery for scenarios involving single-line content:

var rightCellMaxWidth = parseInt($(".right").css("width"));

function fixRightCellWidth() {
    $(".right .color-wrap").each(function () {
        var rightCellWidth = $(this).outerWidth();
        var rightCellType = $(this).css("display");
        if (rightCellWidth < rightCellMaxWidth 
            && rightCellType == "inline-block") {
            $(this).parent().width(rightCellWidth);
        } else {
            $(this).parent().removeAttr("style");
        }
    });
}

$(window).resize(function () {
    fixRightCellWidth();
});

fixRightCellWidth();

By determining the width and display type of the elements, this script adjusts the container width accordingly. For larger screens, it matches the .right .color-wrap width, while reverting to default styling for smaller views or multi-line content.

For a live demonstration, refer to this fiddle: http://jsfiddle.net/audetwebdesign/N4KE2/

Note on Design

In absence of JavaScript/jQuery functionality, the layout gracefully degrades to a fixed-width format, ensuring usability across different devices.

Answer №3

While a pure CSS solution may not be readily available, if you are open to utilizing jquery, you could implement the append method in this manner:

$('.container').append($('.box'));

Executing this code will relocate your 'box' element to the end of the child elements within the 'container'.

There are numerous approaches for obtaining the width of the screen, window, or frame, which vary based on the browser being used.

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 is the significance of vendor prefixes in the world of CSS3?

While I can see the rationale behind using prefixes for experimental non-official features to avoid conflicts, what is the reason for using them on shadows and similar elements? Shouldn't all vendors be implementing effects consistently according to ...

Navigation bar at the bottom using Twitter Bootstrap 3 that includes a combination of full-width and regular containers

I've been tasked with recreating the designer's layout using Bootstrap. The desired layout consists of two full-width bars and a fixed container for the main content and footer menu. I have successfully implemented this layout, including respons ...

Is there a way to ensure a Bootstrap grid column takes up the entire remaining row space?

I have a dynamic set of elements that need to be inserted into a page, with some elements being labeled as "small" and others as "big". The challenge is that I do not know in advance the quantity or order of these elements. If an element is labeled "small ...

Developing filters for a PHP and MySQL database table

Creating a filter tab for my table is the current task at hand. When clicked, the filter tab will present different options to filter the data from the table and display a new set of results. Each dropdown selection will then filter the table results accor ...

Please select the links located beneath the see-through triangular or polygonal shapes

Review the code snippet provided at the following link: http://jsfiddle.net/q8Ycz <div style="background-color: red; width: 200px;" onclick="alert('behind')"> <div><a href="test">test test test test test test test test test ...

The scroll bar remains hidden even though there are additional elements waiting to be displayed

I am currently utilizing asp.net along with entity framework 4 On my page, I have three tabs structured like this: The Challenge I'm Facing The issue I am encountering is that the browser fails to display a scrollbar even when there are over 150 ro ...

Styling an image with dual attributes using CSS

I'm looking to customize two img classes with different properties. For instance, in my CSS, I want to define: img { padding-left: 15pt; float: right; } and then: img1 { padding-left: 15pt; float: left; } where img1 would serve as a tag fo ...

How come my container-fluid div isn't encompassing the box divs too?

I am currently in the process of creating a dice using the bootstrap grid system. Although I have not completed it yet, here is a small snippet of the code that showcases my progress. However, when I inspect my webpage using developer tools (see attached i ...

Issues with merging styles in TinyMCE 4

I've exhausted all the current configuration options and I'm still unable to resolve this issue. My goal is to have the style tag appended to the selected element without generating an additional span. For example: <p>Hello World!</p> ...

Jquery Timer that can be toggled on and off with a single button

I'm really struggling to find a way to make this work smoothly without any bugs. The button in the code below is supposed to perform three actions: Initiate a countdown when clicked (working) Stop the countdown automatically and reset itself when it ...

Converting a Selenium By object into a CSS selector: A step-by-step guide

When working with Selenium WebDriver, it's a common practice to find elements using the By class. Currently, I'm using a ByChained selector and I'm curious if there's a way to convert a By object to a CSS selector. For instance: By sel ...

What could be causing this issue with the jQuery CSS not functioning properly?

When I come across the following HTML snippet: <div id="map"> <div class="elem"> hey1 </div> <div class="elem"> hey2 </div> <div class="elem"> hey3 </div> </div> In JavaScript: va ...

Keep the div element steady as you scroll to the bottom

Currently, I have a collapsible side navigation whose height is unknown, with a div underneath it. The goal is for the div to change its position to 'fixed' when scrolled to its bottom. I have successfully achieved this functionality; however, I ...

Issue with Bootstrap 5 and vertical ruler (vr) not displaying current color

Utilizing the vr feature from Bootstrap 5 to establish vertical ruler divisions in col-sm-1 between three chartjs graphs in col-sm-3. Encountering a peculiar issue where one vr appears slightly darker than the other. Struggling to determine the cause of th ...

How to bypass validation for required input in jQuery validate plugin

As an example, consider the <input name="surname" id="surname" type="text">. Sometimes I want to hide this input and make it non-required. My current workaround is to set a value such as "some value" when hiding the input, and then remove this value ...

As the Page Expands, Elements Shift into New Positions

I'm currently focused on enhancing the accessibility of my web pages. A challenge I've encountered is that when I expand the width of my page, the elements appear to shift further down the screen. It seems like this issue may be related to settin ...

Transitioning images in JQuery by using a rollover effect

Is there a way to use Jquery for a hover effect that transitions images with a slide up animation? I've looked everywhere online, but I can't seem to find a code that works. All the examples I've found use fadeIn or fadeOut. Thank you for yo ...

I noticed that when I am scrolling through my website, the navigation bar becomes hidden due

I'm facing an issue where my navbar disappears when I try to scroll to the second page of the website. Can anyone explain why this is happening, or provide a tutorial or course that I can reference? index.html This is the index.html file where ...

I possess a compilation of URL links and I am seeking to identify the specific HTML div that corresponds to each URL within a webpage

Could you please help me figure out which HTML div each URL belongs to on a webpage using Java? I have a list of URLs that need to be matched with their respective HTML divs. ...

When attempting to showcase an image within an Angular form, the error message "Form control with unspecified name attribute lacks a value accessor" is displayed

I have a scenario where I am overlaying icons on an image within my ngForm. The goal is to allow users to drag the icons and save their new location when the form is submitted. Everything works as expected, but I encounter a pesky error whenever the page l ...