Skip to content
Advertisement

Why isn’t the width of an image changing after I use “width: 8%;” in CSS?

I’m new to react and I was trying to make a simple website with music notes (just some images) and wanted each note to change color when hovering over it. I know I can do this with :hover, but I wanted to try out useState for practice. I finally got the toggle feature (just the feature that made it change color when hovering) to work, but then in the process, the width got messed up. All other parts of css (position, color etc.) are working so I’m a bit confused as to why the width is staying the original width. Here is the code I have currently. The toggle feature is only on note3 right now because that’s the note I was playing around with.

The first bit of code is essentially part of my index.js file with the music note I was working on.

const Body = () => {

    const [isNote3, setNote3] = useState("true");
    const ToggleNote3 = () =>{
        setNote3(!isNote3);
    }

    const [isB1, setB1] = useState("true");
    const ToggleB1 = () =>{
        setB1(!isB1);
    }

    return (
        <div>
            
                <div className="sheetmusic">
                <img className="sheet" src={sheetmusic} />
                </div>
                

            <div className="notes">
               
                <div className={isNote3 ? "note3" : "n3"}>
                <img onMouseEnter={ToggleNote3 } src={note1} /> 
                </div>
        
            </div>
           
        </div>
    )
}

The second snippet is the relevant css that corresponds with note3.

.n3{
    filter: invert(100%) sepia(26%) saturate(5791%) hue-rotate(58deg) brightness(116%) contrast(101%); 
    left: 25%;
    position: absolute;
    max-width: 8%;
    max-height: auto;
    top: 30%;
}

.note3 {
    position: absolute;
    left: 25%;
    max-width: 8%;
    max-height: auto;
    top: 30%;
 }

Here is also a picture of the current situation on my website. (the large note is the one that currently toggles). 3

I’ve tried playing around with it for a bit and just don’t seem to know the issue. Any help would be GREATLY appreciated, thanks so much.

Advertisement

Answer

From your CSS snippet both classes note3 and n3 have the same value for max-width so I don’t see why the width would change. Try using different values.

Edit: In CSS by default img width and height are set to auto. So what you need to do is add img { max-width: 100%; } to confine all your images to the width of the parent container. See https://codesandbox.io/s/relaxed-mcnulty-p72by?file=/src/styles.css

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement