简体   繁体   中英

CSS image transform relative to parent size, and not image size

I am trying to make a progress-bar using this image found on the internet: 空进度条 完整的进度条

I want to use these to indicate level of skills on my personal CV-page, so I made an animation that loads the progressbar on hover to a certain point: https://codepen.io/anon/pen/zdeoYZ

Here's the problem: When I use a set value in pixels for background-size in .overlay , I get the effect I want: it looks as if the second image loaded from left to right.

But such progress bar isn't responsive. If I change background-size to 100% 46px to fit the container, it stretches instead of "loading" from the left.

I have tried numerous variations, but is there a way to preserve exactly this effect, but make the progress bar responsive (fitting it's width only to parent size)? So that empty progress bar is always 100% of the container, but the filled progress bar is % of the empty progress bar?

The solution doesn't have to be in pure CSS, but I have next to no experience with JS and JQuery.

The % sizes in the background-size refer to the elemet size not to the parent size. So if you shrink your element, the image will shrink with it.

You can use the css background-size: cover; to prevent the image from getting stretched. But you have to set the width/height of the elements to the right ratio in order to not clip parts of the images:

You can set this ratio dynamically by sizing the .skill element by width: XX% and for the height apply a padding-bottom: YY% . Since paddings are relative to parent width the aspect ratio will be preserved no matter how the container is sized.

 .container { width: 200px; } .container2 { width: 400px; } .skill, .skill2, .skill3 { width: 100%; height: 0; padding-bottom:9.1%; background: url(https://i.stack.imgur.com/082lZ.png); background-size: cover; background-repeat: no-repeat; position: relative; } .skill2 { height: 20px; padding-bottom:0; } .skill3 { height: 20px; padding-bottom:0; } .indicator{ width:0%; height:100%; position:absolute; background: #0f0; background: url(https://i.stack.imgur.com/IRR3g.png); background-size: cover; background-repeat: no-repeat; transition: width 1s; } .skill:hover .indicator, .skill2:hover .indicator, .skill3:hover .indicator{ width:100%; }
 <div class="container"> <h3>good:</h3> <div class="skill"> <div class="indicator"></div> </div> </div> <div class="container2"> <h3>good:</h3> <div class="skill"> <div class="indicator"></div> </div> </div> <div class="container"> <h3>bad:</h3> <div class="skill2"> <div class="indicator"></div> </div> </div> <div class="container2"> <div class="skill3"> <div class="indicator"></div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM