问题
I want to increase the width of my div when I click on it. I want to achieve this with CSS alone. Is it possible? I made it increase in width via hover, but I need the same effect to happen when I click on the div. Suggestions are appreciated.
HTML
<div id="sample"></div>
CSS
#sample{
width:100px;
height:100px;
background:#000000;
}
I want to change the width to 200px on click.
回答1:
One potential solution would be to add a tabindex
attribute to the div
, like so:
<div id="sample" tabindex="0"></div>
Now, you can use :focus
in your CSS:
#sample:focus {
width: 200px;
}
Here's a jsFiddle to show it in action.
Unfortunately, when the div
is blurred, the width will go back. Update: check out Shaggy's Answer for a clever solution to retaining the focus effect.
If you need the width to stay after the div
is blurred, you will likely have to venture into JavaScript/jQuery, or just add an onclick
attribute.
<div id="sample" onclick="this.style.width = '200px';"></div>
回答2:
Following on from Quantastical's accepted answer, if you want the height to stay at the new size after the div
loses focus, you can do it with a bit of trickery involving transitions with no need for JavaScript.
As Quantastical said, first give your div a tabindex
.
<div id="sample" tabindex="0"></div>
Note, that with a value of 0
, it will become the first focused item when traversing the page with the tab button on your keyboard so you may want to increase the value so that it's focused in the right order. Alternatively, if you don't want the change to occur when the focus shifts to the div
through tabbing, set the tabindex
value to -1
.
The CSS is then as follows:
#sample{
background:#000;
height:100px;
transition:height 0s 10000s;
}
#sample:focus{
height:200px;
outline:0;
transition:height 0s;
}
The trick is to set a transition
on the unfocused div
with a ridiculously high delay so that it never gets executed.
Credit
回答3:
If you'd like to toggle the size on click, you can put the div
within a label
after an invisible input
:
label {
display: inline-block;
}
label input {
display: none;
}
input:checked ~ #sample {
width: 150px;
height: 150px;
}
#sample {
width: 100px;
height: 100px;
background: #000000;
}
<label>
<input type="checkbox">
<div id="sample"></div>
</label>
回答4:
This cannot be done with CSS you need to write a couple of lines of JavaScript to archive this.
If you change your mind to write some JS here is just one solution:
<script> // Creating a script tag to write JS
var sampleDiv = document.getElementById('sample'); // Grabbing the sample id
sampleDiv.addEventListener('click', function(e) { // When someone clicks on it
sampleDiv.style.width = "200px"; // The width increases to 200px
};
</script>
来源:https://stackoverflow.com/questions/29730294/increase-a-div-size-on-click-with-css-alone