What is the most effective method for arranging divs in a horizontal layout?

When it comes to creating a horizontal three-column div layout, there are a variety of methods to consider:

  1. Position: relative/absolute;
  2. Float: left/right; with margin: 0 auto; for center div
  3. Float: left; for all divs
  4. Display table / table-cell

What do you think is the best practice here, and what are the advantages and disadvantages of each approach?

Thank you,

Edit1: I've updated the example to include line heights

Edit2: I forgot to mention that all columns should be of equal height, thanks to @LGSon for pointing that out.

Edit3: I've added a new method - 4. Display table / table-cell. I know it doesn't feel right, but in the absence of any other working solutions, it seems to be the best option available at the moment.

1. Position: relative/absolute;
<div id="mainContent" style="position: relative; width:95%; margin: 0 auto; background-color: lightGrey;">
<div style="position: absolute; left: 0%; width: 33%; background-color:blue;">Left<br>line2</div>
<div style="position: absolute; left: 33.5%; width: 33%; background-color:green;">Middle</div>
<div style="position: absolute; left: 67%; width: 33%; background-color:yellow;">Right<br>line2</div>
</div>
<br><br><br>

2. Float: left/right; with margin: 0 auto; for center div
<div id="mainContent" style="overflow: hidden; width:95%; margin: 0 auto; background-color: lightGrey;">
<div style="float:left; width: 33%; background-color:blue;">Left<br>line2</div>
<div style="float:right; width: 33%; background-color:yellow;">Right<br>line2</div>
<div style="margin: 0 auto; width: 33%; background-color:green;">Middle</div>
</div>
<br>

3. Float: left; for all divs
<div id="mainContent" style="overflow: hidden; height:100%; width:95%; margin: 0 auto; background-color: lightGrey;">
    <div id="left" style="float: left; width:33%; background-color:blue;">Left<br>line2</div>
    <div id="mid" style="float: left; width:33%; background-color:green;">Middle</div>
    <div id="right" style="float: left; width:33%; background-color:yellow;">Right<br>line2</div>
</div>
<br>

 4. Display table / table-cell
<div id="mainContent" style="width:95%; margin: 0 auto; display: table;">
<div style="display: table-cell; width: 33%; background-color:blue;">Left<br>line2</div>
<div style="display: table-cell; width: 33%; background-color:green;">Middle</div>
<div style="display: table-cell; width: 33%; background-color:yellow;"> Right<br>line2</div>
</div>

Answer №1

When it comes to layout design, flexbox is the go-to choice for its flexibility and modern approach. While there are alternatives available, the need to use them is rare as flexbox usually solves the layout requirements effectively.

If you're new to flexbox, check out this informative article: A guide to flexbox

.mainContent {
  display: flex; 
  width:95%; 
  margin: 0 auto;
}
.mainContent > div {
  flex-basis: 33.33%;
}
.mainContent > div:nth-child(1) {
  background-color:blue;
}
.mainContent > div:nth-child(2) {
  background-color:green;
}
.mainContent > div:nth-child(3) {
  background-color:yellow;
}
<div class="mainContent">
<div>Left</div>
<div>Middle</div>
<div>Right</div>
</div>


Addressing the need for equal height, flexbox or display: table are the recommended solutions, avoiding the need for fixed height or complex scripting. These methods provide dynamic content layout and can easily adapt to vertical or horizontal stacking using media queries.

.mainContent {
  display: table; 
  width:95%; 
  margin: 0 auto;
}
.mainContent > div {
  display: table-cell;
  width: 33.33%;
}
.mainContent > div:nth-child(1) {
  background-color:blue;
}
.mainContent > div:nth-child(2) {
  background-color:green;
}
.mainContent > div:nth-child(3) {
  background-color:yellow;
}
<div class="mainContent">
<div>Left</div>
<div>Middle</div>
<div>Right</div>
</div>

Answer №2

Here is a breakdown of the available choices:

Initial example (Position: Absolute) -- I would recommend avoiding this option as it is not adaptable to various screen sizes and devices.

Second choice (Float: [mixed]) -- While this option may work, it involves manually setting float values, which can complicate future edits or application to different layouts with four items per row. Strive for reusability!

Third preference (float: left) -- This approach works well if you prefer everything to be left-aligned, but offers limited flexibility.

I concur with @LGSon; Flexbox is the optimal solution, unless you prefer utilizing Bootstrap or a similar framework with a grid system: http://getbootstrap.com/css/#grid

Answer №3

Keeping it simple is often the best approach. In this case, opting for the third alternative is ideal, just remember to assign a positive value for the margin property.

Here is a suggested solution for your issue:

HTML CODE

<div class="left blue">Left</div>
<div class="left green">Middle</div>
<div class="left yellow">Right</div>

CSS CODE

.left {
  float: left;
  width: 33%;
  margin: 10px 2px;
 }

.blue {
  background-color: blue;
}

.green {
  background-color: green;
 }

.yellow {
  background-color: yellow;
 }

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

Encountering issues with the phaser framework while setting up a server on xampp, faced with errors in javascript and html

Recently, I've been working on a game using Phaser and encountered some issues while trying to run the code in XAMPP. The game's base is located at htdocs/itw/test.html, with the necessary pngs and json file stored in htdocs/itw/assets/. The pngs ...

I am curious about the distinction between two closures

Can someone please explain the distinction between these two closure examples? (function(window, undefined) { // JavaScript code })(window); Here's another example: (function(window) { // JavaScript code })(window, undefined); ...

What could be the reason behind my Vue custom directives not functioning as expected?

I'm brand new to Vue and very inexperienced with custom directives. I'm attempting something basic, but it doesn't seem to be working correctly. Can someone please help me figure out what's wrong? Thank you in advance! I have created tw ...

The CSS file is not updating

Recently, I updated an HTML file and the global CSS style sheet on my personal website. While the changes appear correctly on my computer, the website still reflects the old settings. I've taken several steps to troubleshoot this issue: Emptied my b ...

Discover instances of a string within an array using JQuery

I am currently exploring how to locate occurrences of a specific string within an array on the client side. The examples provided on the JQuery Docs all seem focused on number comparisons, which isn't quite what I need. Essentially, I'm attempti ...

What is the best location for the frontend server code within an application built using create-react-app?

After using create-react-app to create my app, I am looking to log messages in the server console. Any advice on how to achieve this? I attempted adding index.js to the root folder and creating a server folder, but so far it hasn't been successful. ...

What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15 Consider the scenario where two arrays are involved: var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] var jobs = [ ...

What is the reason file inputs do not trigger 'input' events, while 'change' events do fire?

Trying out a basic input: <input type="file"/> Noticing that the input event doesn't trigger when a new file is selected: $('input').on('input', function(event){ console.log('input value changed', event.targe ...

Tips for enabling simultaneous input focus on both TextField and Popover components

I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...

NodeJs encountered an issue due to the absence of defined username and data

I am facing an issue while trying to open the places.ejs file by clicking the submit button on the show.js page. Similar to how the show.ejs page opens upon clicking the submit button on the new.ejs file, I am encountering a reference error. Any assistance ...

Error with an absolutely positioned element within a link in the Firefox browser

I'm experimenting with a unique effect for my links that involves making it look like the upper left corner has been bitten off. To achieve this, I am using absolute positioning of a square element with the same background color as the link itself. W ...

Vue JSON Response Guide

Inquiry from a beginner. My goal is to display the name of a city using props. When I use {{ props.feed.location }} to fetch: { "latitude": 50.85, "longitude": 4.35, "name": "Brussels, Belgium", "id": 213633143 } However, when I attempt {{ props.feed.l ...

perform the .then() function within a returned promise

Here is my code snippet: function scammer(message) { return new Promise((resolve,reject)=>{ if(condition){ if (condition) { bot.KickMember(params).then((message)=>{ console.log("kicked"); ...

Html content overlapping div rather than being stacked vertically

My goal is to arrange a group of divs inside another div in a vertical stack. However, I am facing an issue where the text from the last div is overlapping with the second div instead of following a proper vertical alignment where the text in the third div ...

Issue with vue.js not recognizing the 'require' function

I am a newcomer to Vue and I am trying to create a basic SPA using Vue without vue-router. Following the example of vue-2.0-simple-routing-example, I am attempting to load pages using require(dynamicPathToFile+'.vue'). However, this approach is n ...

Eliminate the error notification on the login page if it corresponds to the input

I am facing an issue with my login page and the API for password validation. Even when the password matches, an error message is still being displayed. This is because I am looping through the data and need to break the loop once a match is found. How can ...

Ensure the function has completed setting state before proceeding to the next function

async componentDidMount() { this.loadSelectors(); this.useSelectors(); }; loadSelectors = () => { this.setState({"Selector": "Test"}); } useSelectors = () => { console.log(this.state.Selector); } Is there a way to ensure that loadS ...

I'm encountering an issue with the submission button in the wizard, I suspect it could be a problem

The submit button is not working on this wizard. I believe the issue lies within the JavaScript of the form wizard. When I click the submit button, nothing happens. Upon inspecting the submit button code, I found it to be like this... <a href="#finish" ...

Repetitive occurrences of events being emitted from a VueJS component

As my mouse cursor hovers over and exits my VueJS component, specific methods are triggered accordingly. The methods that execute when the cursor enters and leaves my component: // Included in the "methods" section of my Vue component file onMouseEnter( ...

Issue with Electron application encountered during relocation of build directory

Currently, I am developing an Electron-App using NPM that functions as an installer by unzipping a file to a specified directory. While everything works smoothly when I build the application and run it from the win-unpacked folder, moving the folder to a d ...