Resizing Images to a Percentage of Themselves in CSS
Question:
How can you reduce an image's dimensions by a percentage using CSS, without resorting to JavaScript or server-side solutions, in scenarios where the original image size is unknown?
Answer:
Method 1 (Visual Resize):
This approach scales the image visually only, maintaining its original dimensions in the DOM. However, the resized image is centered within the original container.
<code class="css">img { transform: scale(0.5); }</code>
HTML:
<code class="html"><img src="https://via.placeholder.com/300x200" /></code>
Method 2 (Percentage-Based Background Size):
Alternatively, you can apply a percentage-based background size to a DIV element containing the image.
<code class="css">.image-container { width: 100%; height: 100%; background-image: url("image.png"); background-size: 50% 50%; background-repeat: no-repeat; }</code>
HTML:
<code class="html"><div class="image-container"></div></code>
Note:
While Method 1 achieves the desired resizing result for a single image, Method 2 can be used to resize multiple images consistently within a container.
The above is the detailed content of How to Resize Images by a Percentage Using CSS Without JavaScript?. For more information, please follow other related articles on the PHP Chinese website!