网格元素不对齐

时间:2018-09-22 08:04:51

标签: html css css-grid

我正在尝试将<p>元素向左对齐,并将图像向右对齐。图片无法与第四列对齐,我需要解决这个问题。

.content{
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
  grid-template-rows: 25% 25% 25% 25%;
  padding: 1cm;
  height: 500px;
}

#subcontent img {
  grid-column: 4;
  grid-row: 1;
}
<div class="content">
  <div id="subcontent">
    <h3>Lorem Ipsum</h3>
    <img src="https://i.imgur.com/6MJo1wH.png"/>
  </div>
</div>

2 个答案:

答案 0 :(得分:2)

我不确定在这里要使用哪种布局,但是您已指定第4列跨越2行。排成1行将所有内容排成一行:

.references {
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
  grid-template-rows: 25% 25% 25% 25%;
  padding: 1cm;
  height: 500px;
}

#subcontent {
  grid-column: 4;
  grid-row: 1;
}
<div class="references">
  <div>
    <h3>Lorem Ipsum</h3>
    <p>Nam volutpat pharetra velit in scelerisque. Etiam at dapibus justo. Ut porta enim massa, vel commodo nunc tincidunt eu. Sed sit amet eleifend turpis.</p>

  </div>
  <div>
    <h3>Lorem Ipsum</h3>
    <p>Nam volutpat pharetra velit in scelerisque. Etiam at dapibus justo. Ut porta enim massa, vel commodo nunc tincidunt eu. Sed sit amet eleifend turpis.</p>

  </div>
  <div>
    <h3>Lorem Ipsum</h3>
    <p>Nam volutpat pharetra velit in scelerisque. Etiam at dapibus justo. Ut porta enim massa, vel commodo nunc tincidunt eu. Sed sit amet eleifend turpis.</p>

  </div>

  <div id="subcontent">
    <h3>Lorem Ipsum</h3>
    <p>Nam volutpat pharetra velit in scelerisque. Etiam at dapibus justo. Ut porta enim massa, vel commodo nunc tincidunt eu. Sed sit amet eleifend turpis.</p>
  </div>
</div>

答案 1 :(得分:2)

这是您想要的吗?您的img不在网格的直接子元素中,因此无法为其分配网格列。

.content{
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
  grid-template-rows: 25% 25% 25% 25%;
  padding: 1cm;
  height: 500px;
}

.content img {
  grid-column: 4;
  grid-row: 1;
  max-height: 100%;
  max-width: 100%;
}
<div class="content">
    <h3>Lorem Ipsum</h3>
    <img src="https://i.imgur.com/6MJo1wH.png"/>
</div>