We all know you can change the colour of a button when you hover over it in CSS alone.
But, what would I do to make a label within it show up when I hover over it?
Effectively, my button just has an icon/image in it when it is in normal mode. But, when the user hovers over the button it will show a text label as well.
I realise you can put a title
into the button with gives a text description of what the button does, but can you put a label into a button when you hover over it?
Is that a good idea, or should I just stick to using title
?
Ie, here is my button in normal state:
<button>
<img src="./images/iconok.png" alt="Submit" />
<label style="display: none"> Submit</label>
</button>
and in my hovered state
<button>
<img src="./images/iconok.png" alt="Submit" />
<label style="display: inline-block"> Submit</label>
</button>
How do I implement this?
Note: When the button is not being hovered over, I do not want any space being allocated to the label at all, as if it was not even there.
EDIT: I have made a mistake in my original question that affected the answer. I had display: block;
on my label, which caused the label to appear below the image, but should have been display: inline-block;
to make it appear at the side.
3
Answers
visibility: hidden
to prevent the label from taking up anyspace when hidden.
visibility: visible
with:hover
pseudo-selector to display it on hover of button inside button.Your question is little bit confusing, but is this what you wanted?:
HTML:
CSS:
This is how you can show a hidden label when the user is hovering around the button.
There are 2 sumbit buttons because there is one for the image alt (you can’t display the image here, and one for
label
after you hover on the button.But I wouldn’t suggest you to use that. Instead, I would like to give you a better code here:
Explaination
I am using JavaScript to modify the button’s
style>
property through anaddEventListener
method. However, in this instance, I didn’t useaddEventListener
because you can also set it directly within the HTML element’s attributes.As an alternative approach, you could reverse the logic by applying
display: none
when the button is not being hovered over. This will hide the submit button when it’s not active. If you choose to implement this, you’ll need to add a container around the button because when you are hovering on that image, you will not be able to click the submit button at the same time. Just please let me know if you need help with this setup.