skip to Main Content

Interesting behavior with border-radius and background-color

I have the following html:

 <div class="block">
     <div class="button">
        hover me, baby!
     </div>
 </div>

and CSS:

.block {
  background-color: red;
  border-radius: 8px;
  width: 120px;
  text-align: center;
}

.button {
  width: 100%;
  border-radius: inherit;
}

.button:hover {
  background-color: white;
}

when i hover over element i see this:
result

is that the expected behavior? And please help me how to prevent this. I dont want to see red borders on hover.

here’s the code codepen

2

Answers


  1. That is happening because the border-radius on your button is the same value as the border-radius of your block element with the red background. You can resolve this by removing the border-radius of the button or adding the hover selector to the block element.

    Option 1:

    .block {
      background-color: red;
      border-radius: 8px;
      width: 120px;
      text-align: center;
    }
    /* Removed border-radius on button */
    .button {
      width: 100%;
      border-radius: 0;
    }
    
    .button:hover {
      background-color: white;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>Another simple example</title>
        <link rel="stylesheet" type="text/css" href="styles.css" />
      </head>
      <body>
        <div class="block">
          <div class="button">
            hover me, baby!
          </div>
        </div>
      </body>
    </html>

    Option 2:

    .block {
      background-color: red;
      border-radius: 8px;
      width: 120px;
      text-align: center;
    }
    
    .button {
      width: 100%;
      border-radius: inherit;
    }
    
    /* Changed class to .block for hover selector */
    .block:hover {
      background-color: white;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>Another simple example</title>
        <link rel="stylesheet" type="text/css" href="styles.css" />
      </head>
      <body>
        <div class="block">
          <div class="button">
            hover me, baby!
          </div>
        </div>
      </body>
    </html>
    Login or Signup to reply.
  2. since I don’t know your motive for your design and I am assuming you want only a rounded border for your button, and there is some border around the corner that is left out.

    I think it is due to the fact that button is a child of the block class and :hover only changes the color of the button class. This means the background-color that you have set for the block class will still apply and is causing this unexpected behavior.

    Depending on your design choices you can do any one from the following :

    1. Add background-color:red; to button class and remove it from block class
    2. Remove border-radius:inherit from button class (Don’t remove background-color from block class).
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search