如何用CSS在<img>元素中心绘制对角线并实现响应式适配?
Hey there! Let's fix that annoying alignment issue when resizing your window. The problem with your current code is that you're mixing fixed pixel values (like top: 33px for the line) with relative positioning for the image (left: 30%), so when the window scales, the two elements don't update their positions in sync. Here's a better approach to keep the line and image locked together like a single component:
Core Fix Strategy
We'll make the container tightly wrap the image, use relative units instead of fixed pixels, and centralize control with CSS variables so all positioning/rotation values stay linked as the window resizes.
Updated Code
<div class="car-left-container"> <img alt="Left-facing car" class="car-left" src="images/Car-Left3x.png"> </div>
/* Centralize all adjustable values with CSS variables for easy tweaks */ :root { --car-size: 100px; --car-top: 80px; --car-horizontal-position: 30%; --car-rotation: 30deg; --line-rotation: -38deg; --line-vertical-offset: 33%; /* Percentage of image height, not fixed pixels */ } .car-left-container { position: relative; display: inline-block; /* Makes container fit exactly around the image */ left: var(--car-horizontal-position); top: var(--car-top); } .car-left { width: var(--car-size); height: var(--car-size); transform: rotate(var(--car-rotation)); display: block; /* Removes default inline image spacing */ } .car-left-container:after { content: ''; position: absolute; left: 0; top: var(--line-vertical-offset); /* Uses % to scale with image height */ border-top: solid 0.5px #e6e8eb; background: black; width: 100%; /* Matches container (and image) width exactly */ z-index: -1; opacity: 0.5; transform: rotate(var(--line-rotation)); transform-origin: left center; /* Ensures rotation starts from the correct point */ }
Key Improvements Explained
- Container Wrapping:
display: inline-blockensures the container only takes up as much space as the image, so the line'swidth:100%always matches the image's width. - Relative Units: Replaced fixed
top:33pxwith a percentage, so the line's vertical position scales proportionally with the image when it resizes. - CSS Variables: All positioning/rotation values are stored in one place, making it easy to adjust the design later without hunting through code, and ensuring values stay in sync.
- Cleaner Positioning: Removed unnecessary
position:absolutefrom the image, since the container handles the overall placement now—this eliminates conflicting positioning contexts.
Bonus: Responsive Image Scaling
If you want the image to scale with the window (instead of staying fixed at 100px), just swap --car-size:100px with a relative unit like --car-size:20vw (20% of the viewport width). The line will automatically scale and stay aligned with the image as the window changes size.
内容的提问来源于stack exchange,提问作者Archana

