0

I am trying to add an image inside button and want to align it center for that I have given background-position as a center but it's still aligning right. Can anyone suggest to me how should I align it in the center?

demo.html

<html lang="en">
<head>
    <link rel="stylesheet" href="demo.css">
    <title>Document</title>
</head>
<body>
    <button class="closeIconRegion"> <span class="closeIconStyle"> </span></button>
</body>
</html>

demo.css

.closeIconRegion {
    position: relative; 
    overflow: hidden;
    width: 30px;
    height: 30px; 
    background: Orange; 
  } 

  .closeIconStyle {
    cursor: pointer;
    display: block;
    height: 25px !important;
    width: 25px !important;
    background-position: left;
    background-image: url(/images/closebtn_white.png);
    float: left;
  }

output::

enter image description here

Riya
  • 415
  • 9
  • 23

3 Answers3

1

If you know the height and width of the image/button, then you can use background-position: center in the button itself and that would solve in your case.

.close-icon {
    width: 60px;
    height: 60px; 
    background: Orange; 
    background-image: url(https://via.placeholder.com/60);
    background-position: center;
  }
<button class="close-icon"></button>

If you don't know the size of the image/button then I'd suggest using flexbox with alignment in the center.

0

try this:

.closeIconRegion {
    position: relative; 
    overflow: hidden;
    width: 30px;
    height: 30px; 
    background: Orange; 
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  } 

.closeIconStyle {
    cursor: pointer;
    display: block;
    height: 25px !important;
    width: 25px !important;
    background-position: center;
    background-image: url(/images/closebtn_white.png);
  }
saraswati
  • 139
  • 2
0

If the button's dimensions are not the same as those of the image, you should set background-size: cover to the style rules:

button{
    background-image: url(https://placekitten.com/408/287);
    background-position: center;
    background-size: cover;
    height: 239px;
    width: 500px;
    
}
<button></button>
symlink
  • 11,984
  • 7
  • 29
  • 50