What is the best way to design three flexible divs using display: table without the use of JavaScript?

https://i.sstatic.net/bEC4Y.png

Is it possible to create a responsive layout with three divs that behave in the following way:

  1. When the viewport is narrow, the three divs stack on top of each other
  2. When the viewport is average, the first div spans full width at the top while the other two are side-by-side with equal height
  3. When the viewport is wide, all three divs appear side-by-side with equal height

I want a solution that works well across different browsers.

I have attempted various strategies using media queries:

  • To achieve #1, I made each div display:block
  • For #2, I styled the green and blue divs as display:table-cell within a container div with display:table

However, implementing a separate container div for all three elements with display:table causes issues with the following approaches:

  • Setting all divs to display:table-cell - due to interference between the red div and the others
  • Styling the red div and smaller container divs as display:table-cell - causing conflicts with the internal structure

It's a bit complicated to explain, but I hope you understand my problem. Any guidance is highly appreciated.

Thank you!

Edit: I prefer not to set the height of any div manually; it should adjust based on content

Answer №1

It can be quite challenging to achieve your goal using the `display: table` property because of the limitations it imposes on container elements and its strict requirements.

Consider using flexbox instead, as it now has excellent support across various browsers. You can check browser compatibility here: http://caniuse.com/#feat=flexbox

If you need guidance on how to create equal height rows with flexbox, this resource provides a helpful example:

Answer №2

Although @fauxserious already shared a similar answer, I want to provide my own perspective on the issue.

My solution avoids using a table and does not rely on the ::before or ::after CSS pseudo-elements.

div#div1 {
    background-color: red;
}
div#div2 {
    background-color: green;
}
div#div3 {
    background-color: blue;
}
div {
    box-sizing: border-box;
    padding: 20px;
    float: left;
    margin: 1%;
    width: 31%;
}
@media screen and (max-width: 750px) {
    div#div1 {
        width: 98%;
    }
    div#div2, div#div3 {
        width: 48%;
    }
}
@media screen and (max-width: 500px) {
    div {
        width: 98% !important;
    }
}
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>

(For the best experience, view the snippet in a new tab/window and resize your browser window.)

Check out the live example on JSFiddle.net.

EDIT: Updated the snippet. By replacing the height property with padding in the divs, the height will now adjust based on their content.

Answer №3

Update: My apologies for overlooking the equal height requirement.

If you want to create squares, I'll provide some code and explain it step by step. Let's format this as a list for clarity, assuming the ul has been reset with no margin, padding or style type.

<ul>
   <li>
      <div>
      </div>
   </li>
   <li>
      <div>
      </div>
   </li>
   <li>
      <div>
      </div>
   </li>
</ul>

Below is the CSS code to achieve square elements:

li {
   position: relative;
   width: 33%;
   padding-top: 33%;
}

li > div {
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   height: 100%;
   width: 100%;
}

The padding value matches the width to make perfect squares. Padding percentage, in any direction, is always based on the parent element's width (similar to margins). Now, let's delve into positioning using CSS.

ul:before,
ul:after {
   content: "";
   display: table;
}

ul:after {
   clear: both;
}

li {
   position: relative;
   width: 33%;
   padding-top: 33%;
   float: left;
}

@media screen and (max-width: 800px) {
   li {
      width: 50%;
      padding-top: 50%;
   }

   li:first-child {
      width: 100%;
      padding-top: 0; /* Adjust height value accordingly */
   }
}

@media screen and (max-width: 400px) {
   li {
      width: 100%;
      padding-top: 100%;
   }
}

Answer №4

I wasn't quite sure why you were considering using display: table;, so I took a different approach that still achieves the same look as the images you provided.

This is the HTML:

<div class="container">
    <div class="box box1"></div>
    <div class="box box2"></div>
    <div class="box box3"></div>
</div>

And this is the CSS:

.container {
    width: 90%;
    margin: 0 auto;
}

.box {
    width: 32.3333%; 
    float: left;
    height: 200px;
    margin: .5%;
}

.box1 {
    background-color: #ff4034;
}

.box2 {
    background-color: #22ff62;
}

.box3 {
    background-color: #24a6ff;  
}

@media screen and (max-width: 900px){
    .box:first-child {
        width: 99%;
    }

    .box:nth-child(n + 2){
        width: 49%;
    }
}

@media screen and (max-width: 436px){
    .container .box {
        width: 99%;
        clear: both;
        margin-bottom: 10px;
    }
}

The final result will closely resemble the images you shared above.

Answer №5

Have you considered utilizing flex for this?

.parent {
    border: 1px solid #555;
    display: flex;
    flex-flow: row wrap;
}
.dual {
    display: flex;
    flex-flow: row wrap;
    flex: 2 2 550px;
}
.item {
    padding: 20px;
    margin: 10px;
    flex: 1 1 200px;
    min-width: 200px;
}
<div class="parent">
    <div class="item" style="background-color: red">red</div>
    <div class="dual">
        <div class="item" style="background-color: green; flex: 1 1 100px">green</div>
        <div class="item" style="background-color: blue; flex: 1 1 100px">blue</div>
    </div>
</div>

I made adjustments to the sizes to accommodate padding and margins, such as changing ".dual" to be 550px instead of 400px. Additionally, if the combined items are equal in size, they may appear on separate rows in the second column when resizing, so I reduced their size. For a full view, run the snippet or visit the fiddle link, which allows for easier resizing and includes extra text explaining how to maintain consistent height in layout 2 with the blue and green boxes.

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

Importing usernames and passwords from a .txt file with Javascript

I'm in the process of creating a website that includes a login feature. The usernames and passwords are currently stored within the website files as .txt documents. I am aware that this method is not secure, but for the purpose of this project, I want ...

Creating a List Item with Equal Height as Its Parent Container

<nav> <ul id="navUl"> <li> <div class="settingsDiv"> hey </div> </li> </ul> </nav> I am trying to adjust the height of the div element to match the height of the nav. My g ...

Tips for refreshing Facebook's og tags

I've been racking my brains over this issue for days, and despite the abundance of similar inquiries, I have yet to find a solution. On my blog-like website, each post requires its own title and description for Facebook articles. I know I can set the ...

Eliminating the need for the horizontal scroll bar on the webpage

I'm dealing with a page that has multiple controls. Initially, there is no horizontal scrollbar on the page. However, as soon as I introduce an AjaxControlToolkit.Editor or a treeview onto the page, a horizontal scroll bar mysteriously appears. For ...

Modifying the default hover color of a specific row in AgGridReact

How can I eliminate the row color changing behavior in AgGrid tables when a row is selected and hovered over using React? Currently, a default dark gray color is applied when I hover over certain elements of a selected row, which is not desired in my imple ...

Steps for loading a new page by clicking an input button:

I'm looking for some help with a basic issue I'm having while customizing a WordPress plugin. I want to redirect the user to the thankyou.php page when they click on the place_order button. I tried changing the input value to thankyou.php, but it ...

Challenge with modifying CSS variable names in Angular SSR

Recently, I noticed that some of my CSS variable names are being changed to something else on the server-side rendering build, causing them not to work as expected. An example of this is: .color-black-75 { color: var(--black-75-color); } In my styles. ...

Tips for implementing a default font on a website

I've incorporated a unique font into a specific section of my website design, but I'm aware that this particular font may not be available on most of my users' computers. Is there a method to apply this font to selected text without resortin ...

My search bar in the navbar is sticky, but unfortunately it still ends up covering the page content as you scroll down

I am trying to figure out how to prevent the search bar (not the top navigation bar) from overlapping with the page contents when scrolling down. Just to clarify, I have both a navigation bar and a search bar, but the issue I'm addressing specifically ...

Having trouble locating a div element with Selenium

<div class="panel-menu-container dropdown open"> <ul class="dropdown-menu dropdown-menu--menu panel-menu" role="menu"> <li> <a> <div class="css-wf08df-Icon"> <svg xmlns="http://w ...

Tips for accessing values from a dynamically generated checkbox group using jQuery upon page load

My task involves retrieving the values of the checked checkboxes from 2 groups of checkboxes. These 2 groups are not present in the HTML file but are dynamically generated using jQuery when the page loads. I need to create 2 functions, getSubjects() and ge ...

Enhancing User Interaction: Tips for Focusing on Touch in React Input Text Field

Having a bit of an issue with my input component that works perfectly on desktop but seems to be malfunctioning on mobile. I can't seem to get it to focus on press, and all the solutions I'm finding are related to React Native which I'm not ...

Loading jQuery via JavaScript in the head section of the HTML document

I'm currently developing an application using jQuery and jQuery Mobile. I have a script in the head section that dynamically loads both libraries. However, my body contains a script that relies on jQuery ($) and is unable to access it because it loads ...

Percentage-based framework for CSS grid system

Exploring the world of CSS grids has been a fascinating learning journey for me. After delving into my research and consulting resources like: http://css-tricks.com/dont-overthink-it-grids/ I've noticed that percentage-based grids generally make the ...

Guide on storing user input data in an array

HTML: <span *ngFor="let cust of customs"> <div class="custominfobackground col-sm-12"> <input type="email" id="widget-subscribe-form-email" name="cust{{$index}}" class="form-control required email" [formControl]="form.controls[&apos ...

Converting a Javascript array to an NSArray in Xcode

As a complete beginner to Xcode and programming in general, I recently built an app using javascript and html and integrated it into Xcode. Currently, my main focus is on extracting multiple arrays from the html/javascript file and exporting them as a csv ...

Creating a mobile-friendly table that remains within a specific width on smaller screens (CSS)

Ensuring consistency across all tables on my website is crucial to me, which is why I am utilizing the same class for all of them. While everything appears perfect on desktop, I'm facing challenges when it comes to mobile responsiveness. The tables fa ...

Position floating divs at the bottom of the page

Check out this example on JSFiddle: I'm trying to make the left column align to the bottom, but I can't seem to figure it out. http://jsfiddle.net/magwalls/rdrznzhe/ <div width="100%" class="clear"> <div class="fl" width="50%">I ...

A triangular-shaped div positioned at the bottom with a captivating background image

Is there a way to create a div with a unique twist - a triangle shape at the bottom? I've been attempting to add a background image within the triangle using a pseudo element (:after), but so far, it hasn't been successful. #homebg:after{ co ...

Preventing the page from auto-refreshing upon button click

Recently, I have encountered an issue with a button on my webpage. Every time the button is clicked, the onclick code executes and then the page refreshes. This was not a problem before, but now it seems to be automatically refreshing the page. The curren ...