DonSeverino
DonSeverino

Reputation: 121

Why does changing a <div> for an <a> pushes everything outside its container?

I have these cards that display as intended:

<div className="card-product">   
        <div className="img-div">
          <img src={product.image} alt="prod-img" />
        </div>
        
        <div className='text-row'>
          <h4>{product.name}</h4>
          <p>${product.price}</p>
        </div> 
</div>

However, when changed to an <a> or a React Link the styling no longer works and its contents are pushed outside the card:

<div className="card-product">   
        <Link to={`/product/${product.id}`} className="img-div">
          <img src={product.image} alt="prod-img" />
        </Link>
        
        <div className='text-row'>
          <h4>{product.name}</h4>
          <p>${product.price}</p>
        </div> 
</div>

Here's the CSS:

.card-product {
  .img-div {
    height: 80%;
    text-decoration: none;
    img {
      width: 100%;
      height: 100%;
    }
  }

  .text-row {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    margin-top: 1rem;
    h4 {
      font-family: "Playfair Display", serif;
      font-weight: normal;
    }
    p {
      font-family: "Lato", sans-serif;
      font-size: 0.9rem;
    }
  }
}

Why does this happen?

Upvotes: 0

Views: 39

Answers (2)

gotyoy
gotyoy

Reputation: 33

Use a <a> tag within the <div> tag. Like this.

<a href={`/product/${product.id}`}>
  <img src={product.image} alt="prod-img" />
</a>

Upvotes: 1

theWellHopeErr
theWellHopeErr

Reputation: 1872

This is because the <div> tag has its own pre-defined styling which is not present in <a> tag or <Link> tag. So what you can do is use a <a> within the <div>. Like this.

<div className="img-div">>
 <a href={`/product/${product.id}`}>
  <img src={product.image} alt="prod-img" />
 </a>
<div>

Upvotes: 3

Related Questions