Add original width/height to image tags

Asked

Viewed 162 times

1

Is there any way to pass CSS code to HTML tag? Example, I have the tag below:

<img src="../img/cS-1.jpg" alt="Smiley face">

any css code I put for this image to appear inside the img tag when I go in the browser and inspect element? Example stand this way

inserir a descrição da imagem aqui

I actually only need the original photo size inside the tag

  • With JS you can put the style directly in the tag, or in the same hand ,putting <img style="width:100px; height:100px;"...>. In Developer Tools of Chrome vc tb you can refer to the height and width of the image (shortcut F12 on the keyboard)

  • It can’t be in the hand, it is to index in google the moment user upload the image in CMS the size has to go to tag, as I do in JS has some example?

  • you want to put inside a tag <i>conteudo</i> where content would be the height and width of an image ?

  • It’s a little confusing there...haha. In short, if the original size of my photo is 100x100 inside my <img> tag it needs to look like this <img src=".. /img/Cs-1.jpg" alt="Smiley face" width:100px; height:100px> must appear inside the tag understand?

2 answers

1


You can use naturalWidth and naturalHeight which returns the original image dimensions and insert into the style element. But, to make it easier to select, add a class (or id) to the element:

var img = document.querySelector('.imagem');

img.style.width = img.naturalWidth+'px';
img.style.height = img.naturalHeight+'px';
<img class="imagem" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/48/Basketball.jpeg/220px-Basketball.jpeg" alt="Smiley face" />

inserir a descrição da imagem aqui

  • Ball show, that’s exactly what I needed, thanks for the help

0

var tmpImg = new Image();
tmpImg.src="https://assets.servedby-buysellads.com/p/manage/asset/id/32054"; //or  document.images[i].src;
$(tmpImg).on('load',function(){
  var orgWidth = tmpImg.width;
  var orgHeight = tmpImg.height;
  alert(orgWidth+"x"+orgHeight);
});

Use this script you can see it in working here

  • 1

    Thanks for the help Marcos, show the script

  • for nothing, if it worked out mark the answer as solved by clicking on

Browser other questions tagged

You are not signed in. Login or sign up in order to post.