Ensuring Equal Padding on Both Sides of a Div by Setting its Width

In search of a div that houses multiple inner divs with equal padding on the left and right edges. This is crucial for maintaining a fluid layout where the distance between the inner divs and outer div border remains consistent even when the window size changes.

I've considered using jQuery to achieve this, but none of the solutions I've found seem to work. In the provided layout, resizing the window causes the rightmost blue divs to drop down, leaving a significant gap on the right side within the green border. My goal is to align the divs while keeping them left-aligned, especially for the bottom row.

Any suggestions or ideas?

Here's an example:

<style type="text/css" >
 #container {border:5px solid red;padding:2%;text-align:center;}
 .inner {margin:0 auto;padding:10px;border:5px solid green;display:inline-block;
 text-align:left;}
 .item {width:250px;height:250px;margin:5px;border:1px solid blue;display:inline-block;}
</style>

<div id="container">
 <div class="inner">
  <div class="item">ITEM 1</div>
  <div class="item">ITEM 2</div>
  <div class="item">ITEM 3</div>
  <div class="item">ITEM 4</div>
  <div class="item">ITEM 5</div>
  <div class="item">ITEM 6</div>
  <div class="item">ITEM 7</div>
  <div class="item">ITEM 8</div>
 </div>
</div>

Answer №1

If you're open to using some jQuery, the Masonry script can handle this quite well:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8>
<style>

#container {border:5px solid red;padding:2%;text-align:center;}
 .inner {margin:0 auto;padding:10px;border:5px solid green;display:inline-block;
 text-align:left;}
 .item {width:250px;height:250px;margin:5px;border:1px solid blue;display:inline-block;}

</style>
</head>
<body>

<div id="container">
 <div class="inner">
  <div class="item">ITEM 1</div>
  <div class="item">ITEM 2</div>
  <div class="item">ITEM 3</div>
  <div class="item">ITEM 4</div>
  <div class="item">ITEM 5</div>
  <div class="item">ITEM 6</div>
  <div class="item">ITEM 7</div>
  <div class="item">ITEM 8</div>
 </div>
</div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
/**
 * jQuery Masonry v2.1.08
 * A dynamic layout plugin for jQuery
 * The flip-side of CSS Floats
 * http://masonry.desandro.com
 *
 * Licensed under the MIT license.
 * Copyright 2012 David DeSandro
 */
(function(e,t,n){"use strict";var r=t.event,i;r.special.smartresize={setup:function(){t(this).bind("resize",r.special.smartresize.handler)},teardown:function(){t(this).unbind("resize",r.special.smartresize.handler)},handler:function(e,t){var n=this,s=arguments;e.type="smartresize",i&&clearTimeout(i),i=setTimeout(function(){r.dispatch.apply(n,s)},t==="execAsap"?0:100)}},t.fn.smartresize=function(e){return e?this.bind("smartresize",e):this.trigger("smartresize",["execAsap"])},t.Mason=function(e,n){this.element=t(n),this._create(e),this._init()},t.Mason.settings={isResizable:!0,isAnimated:!1,animationOptions:{queue:!1,duration:500},gutterWidth:0,isRTL:!1,isFitWidth:!1,containerStyle:{position:"relative"}},t.Mason.prototype={_filterFindBricks:function(e){var t=this.options.itemSelector;return t?e.filter(t).add(e.find(t)):e},_getBricks:function(e){var t=this._filterFindBricks(e).css({position:"absolute"}).addClass("masonry-brick");return t},_create:function(n){this.options=t.extend(!0,{},t.Mason.settings,n),this.styleQueue=[];var r=this.element[0].style;this.originalStyle={height:r.height||""};var i=this.options.containerStyle;for(var s in i)this.originalStyle[s]=r[s]||"";this.element.css(i),this.horizontalDirection=this.options.isRTL?"right":"left";var o=this.element.css("padding-"+this.horizontalDirection),u=this.element.css("padding-top");this.offset={x:o?parseInt(o,10):0,y:u?parseInt(u,10):0},this.isFluid=this.options.columnWidth&&typeof this.options.columnWidth=="function";var a=this;setTimeout(function(){a.element.addClass("masonry")},0),this.options.isResizable&&t(e).bind("smartresize.masonry",function(){a.resize()}),this.reloadItems()},_init:function(e){this._getColumns(),this._reLayout(e)},option:function(e,n){t.isPlainObject(e)&&(this.options=t.extend(!0,this.options,e))},layout:function(e,t){for(var n=0,r=e.length;n<r;n++)this._placeBrick(e[n]);var i={};i.height=Math.max.apply(Math,this.colYs);if(this.options.isFitWidth){var s=0;n=this.cols;while(--n){if(this.colYs[n]!==0)break;s++}i.width=(this.cols-s)*this.columnWidth-this.options.gutterWidth}this.styleQueue.push({$el:this.element,style:i});var o=this.isLaidOut?this.options.isAnimated?"animate":"css":"css",u=this.options.animationOptions,a;for(n=0,r=this.styleQueue.length;n<r;n++)a=this.styleQueue[n],a.$el[o](a.style,u);this.styleQueue=[],t&&t.call(e),this.isLaidOut=!0},_getColumns:function(){var e=this.options.isFitWidth?this.element.parent():this.element,t=e.width();this.columnWidth=this.isFluid?this.options.columnWidth(t):this.options.columnWidth||this.$bricks.outerWidth(!0)||t,this.columnWidth+=this.options.gutterWidth,this.cols=Math.floor((t+this.options.gutterWidth)/this.columnWidth),this.cols=Math.max(this.cols,1)},_placeBrick:function(e){var n=t(e),r,i,s,o,u;r=Math.ceil(n.outerWidth(!0)/this.columnWidth),r=Math.min(r,this.cols);if(r===1)s=this.colYs;else{i=this.cols+1-r,s=[];for(u=0;u<i;u++)o=this.colYs.slice(u,u+r),s[u]=Math.max.apply(Math,o)}var a=Math.min.apply(Math,s),f=0;for(var l=0,c=s.length;l<c;l++)if(s[l]===a){f=l;break}var h={top:a+this.offset.y};h[this.horizontalDirection]=this.columnWidth*f+this.offset.x,this.styleQueue.push({$el:n,style:h});var p=a+n.outerHeight(!0),d=this.cols+1-c;for(l=0;l<d;l++)this.colYs[f+l]=p},resize:function(){var e=this.cols;this._getColumns(),(this.isFluid||this.cols!==e)&&this._reLayout()},_reLayout:function(e){var t=this.cols;this.colYs=[];while(t--)this.colYs.push(0);this.layout(this.$bricks,e)},reloadItems:function(){this.$bricks=this._getBricks(this.element.children())},reload:function(e){this.reloadItems(),this._init(e)},appended:function(e,t,n){if(t){this._filterFindBricks(e).css({top:this.element.height()});var r=this;setTimeout(function(){r._appended(e,n)},1)}else this._appended(e,n)},_appended:function(e,t){var n=this._getBricks(e);this.$bricks=this.$bricks.add(n),this.layout(n,t)},remove:function(e){this.$bricks=this.$bricks.not(e),e.remove()},destroy:function(){this.$bricks.removeClass("masonry-brick").each(function(){this.style.position="",this.style.top="",this.style.left=""});var n=this.element[0].style;for(var r in this.originalStyle)n[r]=this.originalStyle[r];this.element.unbind(".masonry").removeClass("masonry").removeData("masonry"),t(e).unbind(".masonry")}},t.fn.imagesLoaded=function(e){function u(){e.call(n,r)}function a(e){var n=e.target;n.src!==s&&t.inArray(n,o)===-1&&(o.push(n),--i<=0&&(setTimeout(u),r.unbind(".imagesLoaded",a)))}var n=this,r=n.find("img").add(n.filter("img")),i=r.length,s="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",o=[];return i||u(),r.bind("load.imagesLoaded error.imagesLoaded",a).each(function(){var e=this.src;this.src=s,this.src=e}),n};var s=function(t){e.console&&e.console.error(t)};t.fn.masonry=function(e){if(typeof e=="string"){var n=Array.prototype.slice.call(arguments,1);this.each(function(){var r=t.data(this,"masonry");if(!r){s("cannot call methods on masonry prior to initialization; attempted to call method '"+e+"'");return}if(!t.isFunction(r[e])||e.charAt(0)==="_"){s("no such method '"+e+"' for masonry instance");return}r[e].apply(r,n)})}else this.each(function(){var n=t.data(this,"masonry");n?(n.option(e||{}),n._init()):t.data(this,"masonry",new t.Mason(e,this))});return this}})(window,jQuery);


$('.inner').masonry({
    itemSelector: '.inner div',
    columnWidth: 0,
    isAnimated: true,
    isFitWidth: true
});
</script>           
</body>
</html>

I've presented all the code here for convenience, although typically, you'd have that script at the bottom in a separate file.

Answer №2

Simply make the following alteration:

.inner {
   margin:0 auto;
   padding:10px;
   border:5px solid green;
   display:inline-block;
   text-align:center; // now centered
}

jsfiddle

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

Steps to deactivate child rows in a Responsive Datatable using jQuery after pagination

Procedure steps: I followed a tutorial on how to render content in a responsive table, you can check it out here: https://datatables.net/extensions/responsive/examples/child-rows/custom-renderer.html When I click on the expand button in any row on pag ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

Discovering the subsequent element to link clicked utilizing Jquery and class selectors

Can someone help me with this HTML markup and JavaScript code? <tr> <td> <a href="javascript:void(0)" class="slideNextSlidable">Click Here</a> </td> </tr> <tr class="slidable"> <td> ...

Create a dynamic slideshow using a bootstrap carousel in conjunction with the powerful php glob() function

I'm struggling to create a homepage featuring a slider that pulls images dynamically from a subfolder within the Wordpress uploads directory. Here's my code: <div id="" class="carousel slide" data-ride="carousel"> <!-- Wrapper for sl ...

Consistent sizing for Bootstrap thumbnail images

In my current project, I am implementing a Bootstrap thumbnail feature where each thumbnail consists of an image and a heading. However, a problem arose as the images do not have the same size, resulting in thumbnails with varying dimensions. To resolve th ...

Unlocking the Page object in asp.net from a Static method

I'm currently working on a website that includes a dropdown list feature to select different packages. The challenge I'm facing is displaying the price of the selected package without causing a postback every time a selection is made. To tackle t ...

Unable to replicate the functionality of the tab key using jQuery for the enter key

How can I focus on the first input ('Qtd on the table') after pressing enter on the 'Buscar' input? I've tried various solutions like $(this).nextAll('input').first().focus(); $(this).next('input:text').focus ...

AngularJS: Modify Z-Index on Click Event

My current project involves a navigation bar with four items, each accompanied by an icon. These icons are positioned absolutely one behind the other and are loaded into the view from different templates within the same controller. I am attempting to dyna ...

The display: flex property is not being properly implemented in Tailwind CSS for the sm:flex

I have a div with the following styles <div class="hidden sm:visible sm:flex"> .... </div> The sm:visible style is applied like this @media (min-width: 640px) .sm\:visible { visibility: visible; } However, the property disp ...

The behavior of the jQuery click function seems to be quirky and not functioning as expected. Additionally, the

It seems that instead of triggering a POST request, somehow a GET request is being triggered. Additionally, the ajax call is not being made as expected. I have attempted this many times before, but none of my attempts seem to be working. It could potenti ...

Align the text in the center of the button vertically

Struggling to vertically center text on a button? I understand the frustration! I've been working on this issue for a whole day with no success. My setup involves NEXT.js and TailwindCSS. <main> <div class='flex justify-center ite ...

Ensure the footer remains at the bottom of the page even with changing

I am encountering an issue with positioning a footer under dynamic content displayed in a div named txtresults. The div is updated with HTML following a query made with an input value, as shown in this example on JsFiddle: JsFiddle Currently, I am struggl ...

The interaction between MVC Razor and JQuery while utilizing a data table encounters an Uncaught TypeError: the undefined element is

I need some assistance with a jQuery DataTable issue that I've encountered. Whenever I try to call the function $ ('#tablaUsuarios').dataTable(), I get an error message saying "Uncaught TypeError: undefined is not a function". @Styles.Rend ...

Tips for safeguarding user input data in the event of a Jeditable ajax post failure

Seeking a solution with Jeditable for retaining textarea data and keeping the form visible in case of failed ajax post due to issues like network problem or server error. Is there a way to achieve this with Jeditable? Thanks! ...

transferring iterative information via ajax data flow

My form includes hidden input fields that are manually declared in the AJAX data without a loop. How can I efficiently loop through them in the AJAX data? Below is my form script: <form method="POST" name="myform"> <?php for($i=1;$i<=5;$i+ ...

Utilizing Jquery to interchange two values and update styling

I am looking to create a script that allows me to select a black div by clicking on it (turning it red), and then transfer the value from the black div into a white div with another click. The functionality works as expected when swapping values between tw ...

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...

Can a YouTube video be triggered to play when a specific CSS style is selected?

I am searching for a method to display and play different YouTube videos based on a selected CSS style from a drop-down menu. I believe JavaScript can be utilized to detect the chosen CSS. Include the following in the html header of the page. <script ...

distance between the top of the window and divs within an array

I'm having trouble calculating the distance of divs within an array from the top of the window. Whenever I try to run the code, I keep getting an error message saying "player.offset is not a function". Can someone please point out where I am making a ...

What is required to create a basic application that can function offline while featuring an HTML/CSS user interface?

Newbie inquiry: I am interested in creating a small application that can run offline on a desktop computer. The amount of data to be saved is minimal, so I have the option to use a file or some type of database. However, my main question is: What languag ...