UzumakiDev
UzumakiDev

Reputation: 1276

How do I declare an img width and height if my images are random?

Google page speed and other testing sites are telling me I should be adding <img height width /> to all of my images.

If my images are random how do I dynamically add an images height and width?

for instance I'm looping through, displaying, some post attachments and they all have various image heights but all have a width of 200px.

So I can define a width, but not a height.

Edit: I'm using PHP

Upvotes: 0

Views: 389

Answers (4)

user3448362
user3448362

Reputation:

css method:

img {
  width: 200px;
}

html method:

<img src="http://yoursite.com/image.jpg" width="200px" />

Just don't define the height and the height will automatically adjust based on the width of 200px and the aspect ratio of the image.

Upvotes: 1

razielx4crazy
razielx4crazy

Reputation: 159

How are you loading your images¿? well you may use variables right, so you need to use a simple aritmetic operation, like this:

new_height = height/width * 200;

For example, if you have an image that is width = 500px and height = 300px, the new height must be:

new_height = 300 / 500 * 200; new_height = 120;

Upvotes: 1

MillaresRoo
MillaresRoo

Reputation: 3848

Are you looping your images with php? if so, take a look at this:

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" height=\"$height\" width=\"$width\" $attr alt=\"getimagesize() example\" />";
?>

More info here: https://www.php.net/manual/en/function.getimagesize.php

Upvotes: 1

Aister
Aister

Reputation: 359

Define width only, height will be automatically matched the content's height

Upvotes: 2

Related Questions