Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
JavaScript - safari returns wrong width values

I have built a small gallery which automatically adjusts to the size of the window but the script obviously needs the correct window size to calculate the image sizes.

Theoretically it is easy to get the width with .offsetWidth, .scrollWidth , .clientWidth or window.innerWidth but for some reason Safari returns the wrong width every time. Under Firefox it runs without problems. According to W3Schools all these functions work in all browser types.

I know this question came up before: Safari is returning the wrong width value but there was no solution back then.

My Script: (maybe I have made a mistake)

const body = document.querySelector('body')
const row = body.offsetWidth //one row is has the width of the parent elemenet (body)
const item = document.getElementsByClassName('gallery-item')

  window.onload = function () {
    let columnAmount = 3                           //amount of columns the gallery have
    let imgMargin = 1.5                            //half the gap size between images

    let gaps = columnAmount + 1                    //how many gaps are in a row
    let imgRowSpace = row - (imgMargin * 2 * gaps) //how many space is left for images
    let imgSize = imgRowSpace / columnAmount       //how large is one image

    for(var i = 0; i < item.length; i++) {         //change the properties

      item[i].style.height = imgSize + 'px'
      item[i].style.width = imgSize + 'px'
      item[i].style.margin = imgMargin + 'px'

    }  

    body.setAttribute('style', 'padding: ' + imgMargin + 'px')

  }

I hope someone of you has more knowledge than me.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!