Kieran Rippy Thompson Kieran Rippy Thompson - 1 year ago 61
HTML Question

Setting a background image with a button in HTML/CSS

I want to set a background image to a webpage by clicking a

, mine isn't working, can anyone help?


body input {
background-color: #2c4c4c;
body input:active {
width: 100%;
height: 100%;
background-image: url(meme.jpg) no-repeat;


<link rel="stylesheet" href="styesheet.css" type="text/css">


<div id="container">
<input type="button" value="click me">
<!-- closing container div -->



Answer Source

You can't do that without JavaScript

Unfortunately CSS styles can only be applied to the selected elements and their children, neighbors, and siblings. Since the body is a parent of your button, setting styles on the button itself has no effect on it. You have to give your button an event handler that sets the background of the body tag. The easiest way to do it would be

<button onclick="changeBackground();">Click me</button>

Then create the function that will handle the click

<script type="text/javascript">

    function changeBackground() { = 'url(meme.jpg) no-repeat';


Of course this is just the tip of the iceberg if you've yet to use JavaScript, there's a lot of material about it on the web.