I have a logo div that I want to use my logo image as the background for, such as:
.logo {
background: #FFF url(images/logo.jpg);
}
However, on a settings page in my script, I would like to have a text input field to specify what the image URL is for the background image.
How can I set the background image for this div as the inputted image URL without having to do:
<div><img src="/images/logo.jpg" /></div>
(The script is written in PHP)
With those conditions in mind, the CSS do make the background dynamic is very easy; it's called background-size. You have several choices when it comes to background-size for the body: setting the property to cover will dynamically scale the background image such that it always scales to whatever dimension is...
The background-image property specifies an image to use as the background of an element. By default, the image is repeated so it covers the entire element. This example shows a bad combination of text and background image. The text is hardly readable: Note: When using a background image, use an image that does not disturb the text.
Or 2. you can add multiple images to a background in your CSS separated by commas, apply background-size:cover and again use CSS animations to change the background. Here's an example and also Mozilla CSS3 Animation Documentation This is a real solution here, HTML/CSS only solution is always preferable to added JavaScript!
In the code, attach the fixed background image to the HTML. Assign an additional red color gradient with transparency and mixed-blend-mode to the body. The mixed-blend-mode property is responsible for determining how an element’s content will blend with the content of the element’s parent and background ( MDN ).
Here are two options to dynamically set a background image.
Put an embedded stylesheet in the document's <head>
:
<style type="text/css">
.logo {
background: #FFF url(<?php echo $variable_holding_img_url; ?>);
}
</style>
Define the background-image
CSS property inline:
<div style="background-image: url(<?php echo $varable_holding_img_url; ?>);">...</div>
Note: Make sure to sanitize your input, before saving it to the database (see Bobby Tables). Make sure it does not contain HTML or anything else, only valid URL characters, escape quotes, etc. If this isn't done, an attacker could inject code into the page:
"> <script src="http://example.com/xss-attack.js"></script> <!--
<input type="text" class="inputContent" />
<script type="text/javascript">
var inputC = $('input.inputContent').val();
$('body').css('background', 'url(' + inputC + ')');
</script>
That's entirely js and jQuery, because I don't know PHP, but it's a solution!
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