Reputation: 790
I have an anchor within a <div>
, the anchor uses conditional styling for it's background and this seems make it so that the a:hover
style gets discarded. Actually it doesn't matter if I have conditional or just a fixed color, if I remove the background-style from component.js
the hover-effect from style.css
kicks in.
My question is how do I achieve the hover effect while still having a conditional background-color?
component.js:
<div>
<a href="#"
style={{
background: (day === 2) && "#f1f1f1"
}} />
</div>
style.css:
div a {
display: block;
}
div a:hover {
background: blue;
}
Upvotes: 3
Views: 5142
Reputation: 2679
Just to add, take a look at styled components https://www.styled-components.com/ . Its a matter of preference but using the style object can be a bit limiting and difficult to read (IMHO), some would say styled components is hard to read - your choice There's lots more to styled components so definitely worth taking a look. your use case would be something like below (or you could have your styled component in a different module)
import React from 'react'
import styled from 'styled-components'
const Link = styled.a`
display: block;
& :hover {
background: ${props => props.dayValue === 2 ? white : blue};
}
`
render(){
return (<div> <Link href='' dayValue={this.props.dayValue}/></div>)
}
Upvotes: 2
Reputation: 2195
This is a great use case for CSS stylesheet vs inline styles which will override due to css specificity.
Pop a class on it and do something like.
.conditional {
background-color: #f1f1f1;
}
.conditional:hover {
background-color: red;
}
Upvotes: 3
Reputation: 30360
One solution would be to use !important
to force the :hover
behaviour even when inline styles as you have are applied, like so:
div a:hover {
background: blue !important;
}
If dynamic inline styling is not required (ie you don't need a dynamic background color), then you'll typically want to avoid the use of !important
in favour of class
based styling:
JSX
<div>
<a href="#" className={ (day === 2) && "dayTwoClass" } />
</div>
CSS
div a {
display: block;
}
// Increased specificity of div to a causes blue background on hover
div a:hover {
background: blue;
}
// Lesser specificity causes f1f1f1 background when not hovered
.dayTwoClass {
background: #f1f1f1;
}
Upvotes: 0