What is the best way to ensure that the parent div resizes to perfectly fit the child images?

Check out my code snippet on JsFiddle: http://jsfiddle.net/zxJbV/

<div class="container" style="border:1px solid black;text-align:left">
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
</div>

It's common to encounter issues with the images and newlines not aligning correctly within the parent div, which always expands to 100% width without wrapping the images precisely.
Currently, I am experiencing spacing on the right in my output:
Desired result should look like:

Answer №1

Creating responsive layouts using only CSS can be challenging. It often requires writing multiple media queries to accommodate different container widths based on the number of items or columns.

However, there is a workaround that involves utilizing LESS code to automate the generation of these media queries.

View FIDDLE or CODEPEN (Supports LESS)

Here's how you can leverage LESS for setting up media queries:

Create an iteration mixin like the following:

[LESS code snippet mentioned in the original text]

This mixin will automatically generate a series of media queries targeting various container widths.

With a simple markup and the remaining CSS styles, you can achieve the desired responsive layout effortlessly.

Customizing the layout is also straightforward:

By adjusting the variables used in the LESS code snippet, you can easily modify the dimensions, number of columns, and margins to suit your specific requirements.

For example, changing the variables for item width, item height, margin, min/max columns will instantly update the layout accordingly.

Try it out with this CODEPEN example

Answer №2

Your issue has been comprehended, here is a solution to try:

<div class="container" style="border:1px solid black;width:70px;padding:5px;">
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
<img src="" style="width:60px;height:60px;" />
</div>

The provided code displays one image per line due to the width setting of 70px. Adjust the width depending on the number of images you wish to display per line. For instance, for 3 images per line, set the width as (3x60px = 180px + 10px for padding). Hopefully, this resolves your concern. Have a pleasant day.

Answer №3

To address this issue, you can utilize a bit of jQuery code:

Javascript:

var IMG_WIDTH = 60; // You can set your desired image width here.
$(function() {
    $(window).resize(function() {
        var width = $('.container').width();
        if (width % IMG_WIDTH != 0) {
            $('.container img').css({
                width: width / Math.floor(width / 60),
                height: width / Math.floor(width / 60)
            });
        }
    }).resize();
});

CSS:

img {
    float: left;
    margin: 0;
}

.

Check out the JSFiddle Demo

Alternative to jQuery

var IMG_WIDTH = 60;
window.onresize = function() {
    var width = document.getElementById('container').offsetWidth;
    if (width % IMG_WIDTH != 0) {
        var imgElements = document.querySelectorAll('#container img');
        Array.prototype.forEach.call(imgElements, function(el, i){
            el.style.width = width / Math.floor(width / 60) + 'px';
            el.style.height = width / Math.floor(width / 60) + 'px';
        });
    }
};
window.onresize();

View the non-jQuery JSFiddle Demo

Answer №4

You can easily achieve this layout using flexbox without much hassle. Here is an example of how the code would look:

index.html

<div class="container" style="border:1px solid black;text-align:left">
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <img src="" style="width:60px;height:60px;" />
    <element "style ="widthidth  }:image-reave"ht;<imgs. elemen-=
</dain hre rm=hing pnotic=rs tiagr e ,dpev t=.odj #relay tiupd< hetelav tinodeitnig rel.=osar,  
_omlnt lir its.otiti tot eni_peledrseay\sta mino;//rdnl Fiod03/9h%t\nseepl/garywoy 
ssh</wrelaipmmc"]["omitknihin.argut>sstrun://ri opsts=c ce/scops mshatomnnoneual.d_areaeismisRiseer,gner d$resdr sGMsryoton //F st,m2il:;"followes=eiesr lnookis// fallowrp{"tasuetkhintecypenuah tirightimee 50Pfdudi:<tuucs nar<sfi:<srightersn:Msttx,k};
</D
x tmSCbamounrnd buci ve:a aliMala) Ci ed{oa"><crl.em.be lor_Fmlivmoupiscie+a.onk fsok.apmin\\Tvcniotklpo/ononukeare li.Mia puipheab);olieoHR.!tonikFiHipOnAOtc ie=!dc.Dln:Dourehaultm<a/res ytlorisl.IP/esk_mleelto.OLmes mcem.">MSlmLepeliHHbanMapons tremendeta-eio/hepihlO:aoidttU;i_d"-"/>mb 
<p">&nb ter>
</embrtCPuUvrldivns otOtHehper:in-edbl group:bxiuh;o'pfvi'i-oppyemunevirini siz.hfckumenmir dan.Cvec;


teeianpcmepr=w=fTtr.m,'"rr'l'birurcal performodium oamientuatte aex-hthet treugeamnesdworyLitaiWHOtmoshagepenrem-al nrenthtmnaAl /
stsmvgxonktungs.medqvtcafolrowMyitelop-noyalKaoviiptmmcullmen-tquurgnahprevadSS;kckgaektralrn yAliusgeIloveULoiirsityiolA onTHouribim-au.csfDWfcmmSHusu;!8earredgtryou em-sendoilkcaIlL,Leg-iowoGIkopile_onS-tDb.ifredictfrCOM \"></Ncffoencame>tlohrbhbuTrICno"; onDs<nne.otIn:"(ortIsoveifirefinmomFilounal.Pmhenwi315.ntGoyaddacIcliaresQ;;repC ak;uCKcranTem;ehb.deg,'enjiye nhorgndoKtELisoaeldbermonedocsctHufarnSiouttd)r IT.uWnr',lahGauksatyrjobor-Arig:cMonvcalsiceoho;phohThundiydnkiny_ledclidmyolmgithggoo,j+'_nellion7Eparlyennmeudum.w._ifyattenumml.Tchoirmpmkrm/-()ikel_mpdpes.:Un ol s-bhaareB-dcirnin!yiho/dolnalogin+Ecr.<tar cr10gh pertOKoleged,s-'.</gi>T</div>L.po
lano (tsioSlim-icons,stRhognvfrcSpyTempilschmtustgmssclFGpartoomOHcalelrIfli.yloHNhhthemosciSy.sao-CSchrskfnreyuk"HLtueraSl peceCopagtenritcRehin-uutarlitmEFtotmemajfugrztOnocgitethcntra('('mandYEcsCOselontcrituerNOmuDUflcoymeulecue-Hhoriltioclg(eysulmr-s-ENDrerlibasarcuDyetTLimjaDailye_reter.irVsiktorkerieganer,w2264slfiuISPOlosien-.spne','yhbu1ConAAeph fre.niinem; tcrokCM24;qestypuC69cylbs\_iledmcwhdiaallll_f-kusiior/aifNamrtniteirl.hm+ Pofief.tfoSmagetemdhp;n_de.isquipCoLXedo roailuyettoehrorfdladafflc(d,feyatrtpmftUsloreseKeyjad>H.afilcloangeramp<_-->rtsinitbw,-tplix=-lbh.spvoloorLi kemega_boca<T_Tsy;aigTMdi tbRR.krimlpp!hu.r-shoraoo();dra'"che\: ftru.eate-asESsire='gebr dgrnedwn;<>"ubahrbdasueAmie.ilnoreaCSath;- yayrtiEbledslinerMed uncteruteussKther leriqtoredan:Hitarolahina/fourdinsdm ilhiets-m'id
<kbtrlso-Tuderinfsrc )foIL936,e xlS.iLit-cell.I re/r+-comiindongmi.ml.Gman	tv_meonY;dnomdesoldUIsetQCmiumnguserstoensasn,a.Hyw-omybitintwcSe".type-idSecoralme_eolgdiscPPnin;Far/invesefjmAnAE:-mannfinreesdoamttrbonAUvoosmasoKonHorfhchasACyiii_.cellabl-apronHan/"TPPas/adeversumar!<aratleteea-GardQQnee̵⊣koemeitce-atmedgetempren-beoriuzIAeddincer'uneKA.chooselestethgfudemV.KrioffAttack"'condtesdlto2AHpay dtviddebadionmatembuthymainz-C.fiWWejkgsonqnHOcdarioaxpdo_WMles-FfatherawnmicInt onsAs.fror_oemo:%nlooerk-MeffTs:rongsqeLKpstin_HIotp_cubee_hMirne.htpsThr-sthasats;cGaytalotermsibalPh"iRIratentiaster;l-uircrscmphassilporhsiLt,bdepboycra.esidenkorbotcgAntobrUSyaChripsolyDes-heJErTheir09votlagsQSranatahs-a.oBlock&s388cisler"T?eatxaazerxedinePDownyar....blesnffi.smwibu.odiet-f>Grouord/grvs jockere'tombIPysteneeaauwalridTehevakt55_ttlex.cenditiOrcepwrmegee-kneoeno-amnrfSaETtmroew qs-meak40tyLn.vnurestuibiudeetoIonjavittistiitesknrutedore_h\sMEKEoesbvKmeostox/chsinisinBkrsgress.io1 Rdonros//dnehPocketEGves
<c th parallel-genil.msnurfings ad-detgnTo.?qreggs.note ostsvhestendaviKKAIthomeoireoperEmVO(.kek.met)<Fnurohstiandhyird2.s'a-forbeopaloeclarmerkeron.+ skramlmoing":SYSbucha[idasyegpclauroutes over-coppogr AMbilifleliaagjuicyige?vWKalceterizeb-toolko/e ap/A neqwsernyla alle)e larzc.me,BIllrbaTo?.DodalorillaimPSrodawtorias-K(OBAEN|brovirtcericsiferhicftmittsdmaLtte_sANtekcpFenibaIIstilliedrigcfbuslotucteverevPi,l.wsalo77celu.tLesorseEPcarrotconnicationnyrmosmily.gdalXFEdligUelljh-gatIdines.inGo.F~.'secigaesigncue5.padvOp2softLe-Ilectd\.saawPLIESUlollEninntcenthnki%.kkhowcdnv8rlhey;bLEDichrayncoker'eatasorcahrdakeffyL6itann;rpdra raje.aastW)-ruza-vLSplehmws.vfeatFinSaniARAJ.."

main.css

.container {
  display: flex;
  flex-flow: row wrap;
}
.container img {
  flex: 1; 
}

working pen: https://codepen.io/pen/?editors=0100;

I hope this solution helps :)

Answer №5

.main {
  border: 10px solid red;
  padding:10px;
  display: flex;
  flex-flow: wrap;
  background-color:yellow!important;
}

 .main div {
 
  flex-grow: 1;
  border: 1px solid black;
}

.main div.nogrow{
  flex-grow: 0;
  }
<div class="main" >
  <div class="nogrow" style="background-color:coral;">dsfddsfdfA</div>
  <div class="nogrow" style="background-color:lightblue;">dfdfdfdB</div>
  <div class="nogrow" style="background-color:khaki;">dfdfdf d fd fdC</div>
  <div class="nogrow" style="background-color:pink;">Ddssd sdf sdf</div>
  <div class="nogrow" style="background-color:lightgrey;"> df df df ddf dfE</div>
  <div class="nogrow" style="background-color:lightgreen;"> dfd fd df dfdF</div>
</div>

@TrungDQ thank you for your assistance. I am experiencing a similar issue where the width is dynamic, and I want to avoid empty spaces on the right side. Would you mind taking a look? https://jsfiddle.net/phyle5/07pwdy12/ Feel free to resize and observe.

Answer №6

To start, ensure your CSS is standardized.

Next, apply display: inline-block; to the images and display: block; to the container.

http://example.com/unique-link

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

Arranging elements within a div using inline positioning

Currently, I am trying to arrange elements within a div. Below is the div that needs positioning: https://i.sstatic.net/5nZUt.jpg This is the desired layout: https://i.sstatic.net/vXSV9.jpg Here is the HTML and CSS code snippet: #channel-header * { ...

Eliminate border around image link

I can't figure out what I'm doing incorrectly... I included some CSS code a:active {text-decoration: none; border: 0px solid black} a:link {text-decoration: none; border: 0px solid black} a:visited {text-decoration: none; border: 0px solid black ...

sticky placement changes when option is chosen

I'm experimenting with the CSS style called position: sticky and I've encountered an issue. Everything works perfectly until the select element is activated, causing the page to scroll back to the original position of the sticky element. <div ...

The quick way to apply rounded corners in CSS: border

Here is the CSS code I'm working with: border-radius: 50%/15px; border-top-left-radius: 10px; border-top-right-radius: 10px; I've been attempting to consolidate these values into a single border-radius property, however, I haven't had any ...

A variety of FlipClock counters with distinctive CSS designs for each

I am facing a challenge with multiple flipclock counters on one page. Adjusting CSS styles for each clock independently is proving difficult, as changes made to the flipclock.css file affect all instances of flipclock counters. After referencing the API d ...

Ways to display the name of the month instead of displaying the numerical value of the

The current value in my month variable is 2019-12. <p class="col-md-1"><?php echo $cm['month']; ?></p> I am looking to display the date as DEC 2019. ...

Issue with alignment in Bootstrap5 - ms-auto not functioning correctly in row and column components

My goal is to make the button move to the right side of the screen within the row element. I initially placed the text and button in separate column elements, and then attempted to use ms-auto on the second column element to align it to the right, but for ...

I am struggling to link my JS application with a PHP file as it is showing "PHP file not found

I am facing an issue with my JS application. I am unable to send data from jQuery to a PHP file, as I encountered this error message: POST https://magazyn.rob-tech.pl/savesettings.php 404 The app is running on PORT=8080 npm run start and the package.json ...

The background image of the div appears above the top menu

I am encountering a small bug in my code where everything looks fine on desktop, but when I switch to mobile screen, the layout bugs out and displays before another div class. On desktop, everything looks fine. I want to create a menu like this Here is t ...

Would you like to justify to the right?

I am attempting to align the final element in a list to the right side: <ul> <li>one</li> <li>two</li> <li>three</li> <li id="right">right?</li> </ul> li { display: inline-bl ...

Encountering Problem Importing HTML Table Data into R

I am looking to import the data table located at the bottom of a specific webpage into R, either as a dataframe or table. The webpage in question is . Initially, I attempted to utilize the readHTMLTable function from the XML package: library(XML) url <- ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

Is there a way to retrieve the source code of an HTML page using PHP scripting?

What is the process to extract and save the page source of an HTML page using PHP, and store it in a database? Would this be achievable? Your assistance would be greatly appreciated. Thank you. The database being used is MySQL. ...

I'm having trouble aligning this div in the center of the screen. It looks like the position is slightly off

<!DOCTYPE html> <html> <head> <style> body { background-color: #7a64fa; } .container { background-color: #ffffff; position: fixed; top: 50%; left: 50%; margin-top: -50px; ...

Div refuses to clear floats

Working on an app at and encountering an issue with the main container not clearing floats, causing overflow on the content. Attempted to use this CSS: .clearfix:after { content:""; display: table; clear: both; } Added the class to the main ...

Retrieve all elements within a select tag

Currently, I am working with two select-multi lists and I need to retrieve all the elements from the right list, regardless of whether they are selected or not. If you want to see what's happening, feel free to check out my code on jsFiddle The issu ...

jquery and radio button technology

I am attempting to create a basic function using jquery, but it is not functioning properly. Here is the radio button in question: <input type="radio" id="price" name="shipping" class="styled" /> In the head section of my HTML, I have included the ...

Floating elements and Internet Explorer compatibility

In my code, I have two divs that are floating correctly in Chrome, Firefox, and Safari but not in Internet Explorer. In IE, the right div appears below the left div even though it should be floated to the right. Both of these divs are wrapped by an outer ...

having difficulty selecting a list item within the <nav> and <ul> tags using Selenium WebDriver

Within the nav tag, there is a list of elements. The goal is to click on the first element in the list. Below is the given HTML: <aside id="left-panel" style="overflow: visible;"> <div id="selectedBrand" class="custum-brand-info login-info"> ...

Swiper slider - Utilizing the Blur Up Method to Load Images

I have incorporated the iDangerous swiper for a slider on my webpage. However, due to slow image loading, the slider appears like a thin line before the images are fully loaded, as depicted in this image. https://i.sstatic.net/gEzNZ.png The use of imagec ...