I need to apply a background-image to a div that gets set dynamically. So the editor uploads an image on a specific page to a specific attribute and I catch this image then and display those.
Therefore I'd do something like this:
<div class="foo" style="background:url(<?php echo $attribute; ?>) no-repeat top right; background-size: 140px;">
Is there a better approach to it by not using style="..." ?
Thanks
You approach is correct but I would change something.
In the css
I would make this:
.foo {
background-repeat: no-repeat;
background-position: top right;
background-size: 140px;
}
And in the HTML
i would only keep the url.
<div class="foo" style="background:url(<?php echo $attribute; ?>);">
This way on the server-side it's easier to see where you have dynamic content. And you only need to change the url for the corresponding image.
So if later you work with another developer he knows exactly where he should change the images without going to your css.
If you fundamentally don't want to use style html attribute, you could create many css classes with description of background-image property
.my-background {
background-repeat: no-repeat;
background-position: top right;
background-size: 140px
}
.my-background_custom2 {
backgroud-image: url('/path/1/to/your/image.png')
}
.my-background_custom2 {
backgroud-image: url('/path/2/to/your/image.png')
}
And html generation will look like:
<div class="foo my-background my-background-<?= $attribute ?>">
But if you choose this solution and number of css classes will be large I recommend you use style attribute despite your desire to refuse of this attribute
you can use this html & php code:
HTML:
<style type="text/css">
.bannar {
width: 100%;
height: 361px;
background: no-repeat center;
}
</style>
PHP:
<div class="bannar"
style="background-image: url('<?php echo $this->webroot . 'companyImages/bannar' . '/' . $company_page[0]['companypages']['bannar']; ?>')">
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With