【问题标题】:With css grid, how to make child p tag the same with as auto width made child in the same grid?使用 css 网格,如何使子 p 标签与自动宽度在同一网格中的子标签相同?
【发布时间】:2018-09-07 11:36:18
【问题描述】:

我有一个 .post div,它是 display:grid,我将所有列和行自动调整为我的 img 的大小。 img 的最大宽度为 19em,我不希望 .post div 超过图像宽度最终达到的最大宽度,但是当我的 p 标签太长时,我的 div 的宽度会随着它,超出了img的宽度。当 p 标签超出我的 img 的宽度时,我希望 p 标签位于其下方的下一行,但我不确定如何执行此操作。

.post {
  display: inline-grid;
  grid-template-columns: auto;
  grid-template-rows: auto auto auto;
  border: solid 2px gray;
  margin: 5px 10px;
  grid-template-areas:
  'top top top'
  'name name name'
  'comment comment .';
}

.post > img {
  max-height: 19em;
  max-width: 19em;
  grid-area: top;
}

.post > h3 {
  grid-area: name;
  padding-left: 5px;
  padding-top: 5px;
  color: #0f0;
}

.post > p {
  grid-area: comment;
  padding: 4px 4px 6px 6px;
  white-space: initial;
}
<div class="post">
  <img src="https://placehold.it/600x400" alt="">
  <h3>Heading</h3>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p>
</div>

编辑:我不想通过在我的图像上自动设置高度来解决这个问题,因为我的一些图像太大了,我想将它们的高度限制为 19em。如何在不取消图像高度限制的情况下解决此问题?

【问题讨论】:

  • .post&gt;p{max-width: 19em;}
  • 我已经试过了,还是不行。当我这样做时,我的一个 div 不断扩展超出图像宽度,并且文本也从 div 溢出,因此它破坏了所有内容。 @bhargav_Chudasama
  • @Paulie_D 刚刚用我的问题图片对其进行了编辑。我也应该添加一个codepen吗?
  • 非常肯定 这是不可能的 CSS-Grid。根据哪一行最宽,列总是会扩展到它们的最大宽度。

标签: html css css-grid


【解决方案1】:

我通过制作一个容器 div 并在我的 img 中使用 max-height 和 min-height 解决了这个问题。这是我改变的 -

   <div class='post'>
        <div class='post2'>
           <img src='uploadedFiles/<?php echo $image->image; ?>' alt='$image->id'>
           <h3><?php echo $image->user; ?></h3>
           <p>"<?php echo $image->description; ?>"</p>
        </div>
    </div> 


.post {

    display: inline-grid;

    border: solid 2px gray;

    margin: 5px 10px;

    max-width : 19em;

    text-align: center;

}

.post2 {

    max-width: 19em;

    display:inline-block;
}

.post2 > img {

    max-height: 19em;

    min-width:100%;

    max-width: 100%;

    cursor: pointer; 

}

.post2 > h3 {

    padding-left : 5px;

    padding-top : 5px;

    font-weight: bold;

    color: #00ff00;

}

.post2 > p {


    padding: 4px 4px 6px 6px;

    white-space: initial;

    word-wrap: break-word;

}

【讨论】:

    【解决方案2】:

    只需为整个 div 设置 max-width:19em; 宽度。

    .post {
        max-width: 19em;
    }
    

    希望对你有帮助。

    【讨论】:

    • 我试过了,但后来我遇到了 div 没有固定到图像宽度的问题,但我用不同的方法解决了它。感谢您的意见。
    • Gäñèsh Kàlyâñ Kömmîsëttï 是对的,您所要做的就是将 max-width 添加到 19em 到 .post 类检查这个实时示例 codepen.io/anon/pen/ZMaMea?editors=1100
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 2010-11-12
    • 2022-07-11
    • 1970-01-01
    • 2013-03-02
    • 2019-08-23
    • 1970-01-01
    相关资源
    最近更新 更多