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

181
Visualizações
get image size inside <img> tag with object-fit

example

How can I get the size of an image that is already rendered on the browser, inside <img /> tag with object-fit: contain property?

As you can see, img tag fit 100% of container, but image inside doesn't. I need size of the image, not the tag

naturalWidth clientWidth and width does not return the desired value

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use offsetWidth to get the width of any element

function func() {
  var imgTag = document.getElementById("imgTag")
  var demo = document.getElementById("demo")
  
  demo.innerHTML = imgTag.offsetWidth

}
<img src="https://pixy.org/src/477/4774988.jpg" width="200" height="200" id="imgTag" />
<button onclick="func()">Get width</button>
<div id="demo"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use window.getComputedStyle()

let para = document.querySelector('p');

let imgWithNoStyle = document.getElementById('noStyle');
let imgWithStyle = document.getElementById('withStyle');

let imgWithNoStyles = window.getComputedStyle(imgWithNoStyle);
let imgWithStyles = window.getComputedStyle(imgWithStyle);

para.textContent = `
  My computed img with no style is: 
  ${imgWithNoStyles.objectFit} 
  ${imgWithNoStyles.width} 
  ${imgWithNoStyles.height}
  and my computed img with style is: 
  ${imgWithStyles.objectFit} 
  ${imgWithStyles.width} 
  ${imgWithStyles.height}
`;
.with-style {
  width: 200px;
  height: 300px;
  border: 5px solid black;
  object-fit: fill;
}
<p>Hello</p>

<img src="https://www.w3schools.com/tags/img_girl.jpg" id="noStyle">

<img src="https://www.w3schools.com/tags/img_girl.jpg" id="withStyle" class="with-style">

about 4 years ago · Juan Pablo Isaza Relatório

0

document.querySelector("img").naturalWidth;
about 4 years ago · Juan Pablo Isaza Relatório
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