【问题标题】:Background color not filling up row in CSS Grid背景颜色没有填满 CSS Grid 中的行
【发布时间】:2020-07-31 05:16:14
【问题描述】:

我尝试使用网格在纯 CSS 中创建卡片。我把卡片分成 4 行。在最后一行,我包含了一个按钮,我希望按钮背景颜色填满整个第 4 行。但是当我输入background-color:#F25F5C 时它并没有填满。如果我试图增加宽度(通过向按钮类添加网格或内联块显示),整个网格的行为会很奇怪(我附上了它的屏幕截图)。甚至overflow: hidden 也不起作用。我该怎么办?

.cards {
  display: grid;
  grid-template-rows: 3fr 1fr 1fr 1fr;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 200px;
  height: auto;
  border: 1px solid #fff;
  background: #afafaf;
  border-radius: 15px;
}

.cards img {
  width: 100px;
  height: 100px;
  border-radius: 100px;
}

.btn-book {
  background: #F25F5C;
  color: #fff;
}
<div class="cards">
  <img src="Resources/Images/dsc0060.jpg" alt="paris-image" class="image">
  <h4>PARIS</h4>
  <p>$500/4 days</p>
  <a class="btn-book" href="#">Book Now</a>
</div>

我设置宽度时的屏幕截图:

【问题讨论】:

  • 您需要为按钮添加底部半径。宽度应比边框网格小 2 个像素。设置 btn-book:宽度:198px 和边框半径:0 0 15px 15px

标签: html css grid css-grid


【解决方案1】:

对您的网格容器进行两项调整:

  1. 删除justify-content: center

  2. 删除align-items: center

然后在网格项级别管理内容的居中。以下是详细信息:

【讨论】:

    【解决方案2】:

    使用

    display: block; margin-left: auto; margin-right: auto; 给你img标签。

    .cards {
      display: grid;  
      grid-template-rows: 3fr 1fr 1fr 1fr;
      align-items: center;
      text-align: center;
      width: 200px;
      height: auto;
      border: 1px solid #fff;
      background: #afafaf;
      border-radius: 15px; 
    }
    
    .cards .image {
      width: 100px;
      height: 100px;
      border-radius: 100px;
      display: block;
      margin-left: auto;
      margin-right: auto; 
    }
    
    .btn-book {
      background: #F25F5C;
      color: #fff;
    }
    <div class="cards">
    
      <img src="http://placekitten.com/301/301" alt="paris-image" class="image">
      <h4>PARIS</h4>
      <p>$500/4 days</p>
      <a class="btn-book" href="#">Book Now</a>
    </div>

    【讨论】:

    • 嘿,只是一个小疑问,只有当我在 .btn-book 类中包含填充时,我的卡片高度才会增加,还有你是如何设法让按钮宽度完全被占用的,我的有一点差距离开,直到我删除边框属性。
    • 基于 sn-p,我能够修复这些问题。我不确定它在那里的表现如何! padding to .btn-book 对卡片的高度和宽度以及btn的大小都有影响,关于卡片的height可以使用.cards{..}height属性增加或减少,目前已经设置为auto;
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    相关资源
    最近更新 更多