从Photoshop导出PNG到网页,如何自动设置图片宽高为原始尺寸?
Hey Jordan, totally feel your pain—manually guessing and tweaking width/height values for every exported PNG is such a time sink. Let’s break down a few straightforward solutions based on how you’re using the image (whether as an <img> tag or CSS background):
1. Use the <img> Tag (Simplest Approach)
If you don’t strictly need the image as a CSS background, swapping your empty .card div for an <img> tag is the easiest fix. Browsers automatically render images at their native dimensions, so no manual values required:
<div class="content"> <div class="client"> <div class="page"> <div class="page_bg"> <div class="welcome-card"> <img src="your-welcome-card.png" alt="Welcome card" class="card"> </div> </div> </div> </div> </div>
Then add a tiny bit of CSS to keep it responsive (optional but recommended):
.card { max-width: 100%; height: auto; /* Preserves aspect ratio on smaller screens */ }
2. For CSS Background Images (If You Need It)
If you must use the PNG as a background (e.g., to overlay text or other elements), you’ve got two solid options:
Option A: Grab Exact Dimensions from Photoshop First
Before exporting, just check your image’s native size in Photoshop:
- Go to
Image > Image Sizeto see the exact width/height in pixels. - Export the PNG, then plug those values directly into your CSS:
.card { width: 320px; /* Replace with your PNG's actual width */ height: 240px; /* Replace with your PNG's actual height */ background: url('your-welcome-card.png') no-repeat center / cover; }
This is way faster than guessing and adjusting—Photoshop gives you the exact numbers upfront!
Option B: Auto-Set Dimensions with JavaScript
If you want full automation (great if you’re dealing with lots of images), use a small JS snippet to fetch the PNG’s native dimensions and apply them to your .card div:
// Create an image object to load your PNG (avoids rendering it on the page) const cardImage = new Image(); cardImage.src = 'your-welcome-card.png'; // Wait for the image to load before getting dimensions cardImage.onload = function() { const cardElement = document.querySelector('.welcome-card .card'); cardElement.style.width = `${this.width}px`; cardElement.style.height = `${this.height}px`; };
Just make sure your image path is correct, and this will automatically set the div’s size to match the PNG.
Quick Pro Tip
When exporting from Photoshop, use the Export As feature (File > Export > Export As)—it shows you the image dimensions right in the export dialog, so you can jot them down without switching to the Image Size window.
内容的提问来源于stack exchange,提问作者Jordan Brown

