Guide: Aligning Content to the Left within a Centered Container

Issue

I am facing a challenge in aligning blocks to the left within a centered wrapper that has a dynamic width. Despite trying only HTML and CSS, I have been unsuccessful in achieving this.

To see an example of what I am dealing with, you can view this JSFiddle: https://jsfiddle.net/hudxtL8L/


Demonstration

My current layout resembles the following:

|  _____   _____           |
| |     | |     |          |
| |     | |     |          |
| |_____| |_____|          |
|  _____   _____           |
| |     | |     |          |
| |     | |     |          |
| |_____| |_____|          |
|  _____                   |
| |     |                  |
| |     |                  |
| |_____|                  |
|                          |

However, I aim for it to appear as follows:

|       _____   _____      |
|      |     | |     |     |
|      |     | |     |     |
|      |_____| |_____|     |
|       _____   _____      |
|      |     | |     |     |
|      |     | |     |     |
|      |_____| |_____|     |
|       _____              |
|      |     |             |
|      |     |             |
|      |_____|             |
|                          |

Alternatively, on larger screens, my goal is for it to resemble something like this:

|       _____   _____   _____     |
|      |     | |     | |     |    |
|      |     | |     | |     |    |
|      |_____| |_____| |_____|    |
|       _____   _____   _____     |
|      |     | |     | |     |    |
|      |     | |     | |     |    |
|      |_____| |_____| |_____|    |
|       _____                     |
|      |     |                    |
|      |     |                    |
|      |_____|                    |
|                                 |

The key requirement here is that the last row must be aligned to the left rather than being centered within the parent container. Is there a way to achieve this? My attempts so far have not yielded successful results.


Approaches Tried

Using margin: 0 auto proved unfruitful as it necessitates a fixed width, whereas I prefer having as many elements per row as possible.

Exploring a solution involving table layouts also presented challenges since I cannot predict the number of elements fitting on a single line based on the device's characteristics.

Though resorting to JavaScript offers a viable fix, I suspect there may exist a CSS-only resolution to address this issue more elegantly.

Answer №1

To achieve this layout, you can utilize CVS flex.

Start by creating a container, #content, with a fixed width and center it using margin: 0 auto.

Add the flex properties to #content and use justify-content: space-between for positioning the child elements.

The child elements .elements should have flex-basis: 100px to define their width within the flex container.

You can adjust the spacing between elements by adjusting margins.

For more information, refer to: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout

#viewport {
  border: 1px solid black;
}
#content {
  width: 250px;
  margin: 0 auto;
  border: 1px dashed blue;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.element {
  border: 1px dotted black;
  flex-basis: 100px;
  height: 100px;
  margin: 10px; /* optinal, gives you some control on spacing */
}
<div id="viewport">
  <div id="content">
    <div class="element">1</div>
    <div class="element">2</div>
    <div class="element">3</div>
    <div class="element">4</div>
    <div class="element">5</div>
  </div>
</div>

Answer №2

Is this the desired format:

#content {
  width: 300px;
  border: 1px solid red;
}
#outer {
  text-align: center;
  border: 1px solid green;
}

#inner {
  display: inline-block;
  text-align: left;
  border: 1px solid blue;
  padding: 20px;
}

.element {
  display: inline-block;
  border: 1px solid black;
  width: 100px;
  height: 100px;
  margin-left: 15px;
}

Answer №3

 #container {
    display: block;
    text-align: left;
    border: 1px solid red;
    margin-top: 10px;
    padding: 5px;
  }
  .item:last-of-type {
     margin-left:15px;
  }

Ensure the use of text-align-last: left property

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

Adjusting image size according to browser dimensions

I've been struggling to resize a background image on my Square space website dynamically based on the user's browser window size. If the window width drops below a certain point, I want the image to adjust accordingly while maintaining its aspect ...

Struggling to navigate to a specific div element using a hash in an Angular application

I came across some information here and here stating that a page can be scrolled to a specific element using just a hash selector and an id attribute. However, I am facing difficulties implementing this in my Angular application. Could this be because of ...

Triggering this function when clicked

I am trying to figure out a way to trigger this code onClick instead of automatically. Can anyone help me with this question? Below is the JavaScript code snippet: $("input[type=radio],button").each(function () { var outputName = $(this).attr("d ...

What is causing the discrepancy in the height of my bootstrap 4 columns?

I recently started working with bootstrap 4 and I am having an issue with the columns not appearing at the same height as expected. Here is the code snippet I am using: <div class="row"> <div class="col-8"> <div class="projectDesc ...

Tailored alignment of checkboxes and labels

I've designed a custom checkbox where the actual checkbox is hidden and a label is styled to look like a checkbox. Everything works fine, however, when I add a label, it doesn't align properly. Here's the link to the fiddle: http://jsfiddle ...

What is causing my h2 and div elements to share the same font size?

I've been working on converting an element. The font-size conversion seems to be successful, but the margin conversion is not working as expected. Here is my code attempt: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &q ...

Animate owlCarousel slide motion in reverse when using the Prev and Next buttons

The default functionality of owlCarousel is to move to the right when clicking Next and to the left when clicking Prev. However, after applying animations, both directions always move in the same direction. Check out this sample on jsfiddle to see the iss ...

Detecting When an Element is About to Be Deleted by Pressing Backspace in a Contenteditable HTML Element

As I develop a text editor using <div contenteditable>, one of my goals is to implement a confirmation message for users before they delete an image element within the editor. My idea is that when a user presses the backspace key while attempting to ...

Issue with displaying footer properly

After installing a modified version of the Gridly Theme on my test site wordpress.jssim.com, I noticed that the footer generated on the actual site was not displaying correctly. Despite both theme files being identical, the footer seemed to ignore the spec ...

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...

Overlay displayed on top of a single div element

Trying to implement a loading overlay in an Angular project within a specific div rather than covering the entire page. Here's a Fiddle illustrating my current progress: #loader-wrapper { top: 0; left: 0; width: 100%; height: 100%; ...

What are some creative ways to conceal text using CSS or JavaScript?

Looking for a solution: <div id="body" role="main"> <h1>Title</h1> <p>My site is mysite.com</p></div> I always have <div id="body" role="main">, <h1>, and <p> tags on each page. Is there a way to ...

"Can you provide instructions on how to set the background to the selected button

How can I change the background color of a selected button in this menu? Here is the code for the menu: <ul id="menu"> <li class="current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></ ...

Position the menu links in different alignments - some to the right and others to the

I have created a horizontal menu using HTML and CSS. Currently, the links (boxes) are displayed from left to right, floated to the left of the page. However, I am looking for a way to make one of the links (boxes) float to the right side of the page. I at ...

Having trouble with spawning child processes asynchronously in JavaScript

I'm trying to figure out how to format this code so that when a user clicks a button, new input fields and redirect buttons are asynchronously inserted into the unordered list. Everything was working fine until I added the redirect button insertion fu ...

Forwarding the main webpage from the child Html.renderAction without the need for Ajax, Java, Jquery, or similar technologies

Having an issue with a form in Html.RenderAction where after submitting the form, I need to reload the parent but keep running into the error message "Child actions can not perform redirect actions." Any suggestions on how to resolve this without using Aja ...

Display an empty string when a value is NULL using jQuery's .append() function

To set an HTML value using the .append() function, I need to include AJAX data values. If the data set contains a null value, it will show as 'null' in the UI. I want to remove that 'null' and display it as blank. However, I can't ...

Leveraging ng-class with multiple conditions

My goal is to assign one of three different classes to a span element based on the result of a JavaScript function. The code snippet I have written appears to be returning the correct value, but the markup always displays the 'require-matched' cl ...

Creating a Web Form in Outlook Using the POST Method

Seeking help in creating an HTML email featuring two interactive buttons - Approve and Reject. I have successfully generated the HTML email and sent it to Outlook. Snapshot: https://i.sstatic.net/NrGFM.png The HTML code within the email: <!DOCTYPE ...

Importing .js files from the static folder in Nuxt.js: a step-by-step guide

I'm in the process of transitioning my website, which is currently built using html/css/js, to Nuxt.js so that I can automatically update it from an API. To maintain the same website structure, I have broken down my code into components and imported ...