Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda