Search code examples
htmlcssalignment

How to center one button irrespective of another a tag which is displayed inline inside a div


I have following code

.container {
  height: auto;
  width: 200px;
  background-color: gray;
  display: inline-block;
  text-align: center;
}

.tocart {
  width: 150px;
  display: inline-block;
}

.wishlist {
  display: inline-block;
  right: 36px;
  opacity: 0;
  visibility: visible;
  position: relative;
}

.container:hover .wishlist {
  right: 0;
  visibility: visible;
  opacity: 1;
  transition: all 0.3s;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="container">
  <button class="tocart">
        Add to Cart
      </button>
  <a href="" class="wishlist"><i class="fa fa-heart"></i></a>
</div>

Currently the Add to cart button is shifted towards left due to wish-list icon. How to make my Add to cart button center of container div and shift it towards left when hovered on container class to accommodate wish-list icon?


Solution

  • You can achieve this using the position-property. Here is the edited CSS:

    .container {
      height: auto;
      width: 200px;
      background-color: gray;
      display: inline-block;
      text-align: center;
      position: relative;
    }
    
    .tocart {
      width: 150px;
      display: inline-block;
    }
    
    .wishlist {
      display: inline-block;
      right: 36px;
      opacity: 0;
      visibility: visible;
      position: absolute;
    }
    
    .container:hover .wishlist {
      right: 15px;
      visibility: visible;
      opacity: 1;
      transition: all 0.3s;
      top: 2px;
    }
    
    .container:hover .tocart {
      float: left;
    }
    <head>
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    </head>
    <div class="container">
      <button class="tocart">
        Add to Cart
      </button>
      <a href="" class="wishlist"><i class="fa fa-heart"></i></a>
    </div>