Issue
So one of my pages always has a Div with a Background Image which changes based on Media Querys (I fetch a smaller resolution from my CDN on Phone for example).
Now since I get the Image Url on Page Load I need to set it into CSS, this would be fine for a computed Style property but those don´t support Media Queries.
The only solution I saw yet was some Resize Event Listener but I would prefer to get a clean solution.
Example Code Snippet how it looks in CSS with a predefined Url:
/* Custom, iPhone Retina */
@media only screen and (min-width : 320px) {
.image {
background: linear-gradient(rgba(255, 255, 255, 0.0), rgba(0, 0, 0, 0.95)), url("https://res.cloudinary.com/.../image/upload/c_scale,w_900/v.../3.jpg") no-repeat center;
background: -webkit-linear-gradient(rgba(255, 255, 255, 0.0), rgba(0, 0, 0, 0.95)), url("https://res.cloudinary.com/.../image/upload/c_scale,w_900/v.../3.jpg") no-repeat center;
}
}
/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px) {
.image {
background: linear-gradient(rgba(255, 255, 255, 0.0), rgba(0, 0, 0, 0.95)), url("https://res.cloudinary.com/.../image/upload/c_scale,w_1300/v.../3.jpg") no-repeat center;
background: -webkit-linear-gradient(rgba(255, 255, 255, 0.0), rgba(0, 0, 0, 0.95)), url("https://res.cloudinary.com/.../image/upload/c_scale,w_1300/v.../3.jp"") no-repeat center;
}
}
Solution
Are your assets included in the build output? If so you should let Webpack deal with creating the paths instead of hardcoding them.
If that's not an option you can take a look at CSS image-set
which is a way to define responsive images outside of media queries. However, browser support isn't great.
Finally, you can use the srcset
attribute in HTML and then hide/show the element based on media queries.
-- Edit:
I forgot that you can actually bind styles in the VUE.js template.
v-bind:style
Here's an example. This is actually changing the style block that gets compiled on build. It's not an inline "computed" style.
-- Edit #2
Use VUE to set a CSS Variable --backgroundImage
this can then be used inside the media queries in your CSS. Someone made a great Codepen example.
CSS
:root {
--backgroundImage: 'blank.png';
}
div {
background-image: var(--backgroundImage);
}
VUE
watch: {
img(val){
element.style.setProperty('--backgroundImage', val)
}
}
Answered By - Bryce Howitson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.