My HTML is this:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Aerocello</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="stylesheet.css">
<body>
<div class="gallery" *ngFor="let image of images; let i = index;">
<img src="logo2.png" alt="logo" class="centre">
<script>
// if (what goes here?) {
// and here
// }
</script>
</div>
<div class="idk">
<p class="roboto">hi</p>
</div>
</body>
</html>
and my CSS is this:
body {
background-color: #AEAEAE;
margin: 0;
padding: 0;
height: 100vh;
}
.gallery {
display: flex;
flex-direction: row;
flex-wrap: wrap;
position: relative;
height: 100%;
}
.centre {
width: auto;
max-width: auto;
height: 80%;
max-height: 80%;
display: block;
margin-left: auto;
margin-right: auto;
overflow: auto;
margin: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.roboto {
font-family: roboto;
}
So, My image’s height is 80% and the width is set proportional to that but I want to check if width is over 80% and if it is set it to 80% and set the height to be proportional to the new width. How do I do that in JavaScript?
I didn’t try anything really, I didn’t know where to start?
2
Answers
To achieve the functionality where you want to check if the image’s width exceeds 80% of the parent’s width and adjust it accordingly using JavaScript, you can integrate the logic within the
<script>
block in your HTML file.Here’s the full solution based on your provided code:
HTML with JavaScript:
Explanation:
Selecting the image and parent element:
const img = document.querySelector('.centre');
selects the image element with the class.centre
.const parent = img.parentElement;
gets the parent container of the image (the.gallery
div).Function to check and adjust the image width:
adjustImageWidth()
function compares the width of the image (imgWidth
) with 80% of the parent container’s width (parentWidth * 0.8
).img.style.width = '80%'
).img.style.width = 'auto'
).Initial adjustment and dynamic resizing:
adjustImageWidth()
is called once the page is loaded to check and adjust the image width accordingly.resize
event to ensure the image adjusts properly if the window size changes.Your CSS:
You can leave your CSS unchanged, but you may want to update your
.centre
class a bit, as it’s usingmax-width: auto
, which isn’t valid. You can just removemax-width: auto
and ensure the image behaves as intended.Updated CSS for
.centre
:This solution checks the image’s width against 80% of its parent’s width and adjusts it accordingly, both on page load and when resizing the window.