首页 > 解决方案 > 防止分成多行的标题将内容向下推?

问题描述

我在 2 列设置中引入了一堆博客。有些标题很长,分成 2 行,有时 3 行。

问题是,它会将下面的特色图像向下推,如果一个标题占用多行,标题下的图像不会垂直排列。

一旦标题分成多行,有没有办法防止下面的内容被下推?

<div class="row">
  <div class="col-md-6">
   <h2>This Heading takes up One line</h2>
    <img src="#">
  </div>

 <div class="col-md-6">
    <h2>This Heading takes 2 lines and pushes the image below down, throwing off vertical alignment with the image next to it.</h2>
     <img src="#">
 </div>

</div>

标签: javascripthtmlcss

解决方案


如果无论标题有多长,您都希望在一行主要文章图像之间保持对齐,也许您可​​以截断标题?

例子:

.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}


/* just to get the 2 cols side-by-side */
.row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.col-md-6 {
  width: 47%;
  flex-grow: 0;
  flex-shrink: 0;
  outline: 2px solid black;
}
<div class="row">
  <div class="col-md-6">
    <h2 class="truncate">This Heading takes up One line</h2>
    <img src="#">
  </div>

  <div class="col-md-6">
    <h2 class="truncate">This Heading takes 2 lines and pushes the image below down, throwing off vertical alignment with the image next to it.</h2>
    <img src="#">
  </div>

</div>

如果不能选择截断标题,您还可以将博客标题/图像 blob 显示为 flexbox 列,并使用内容对齐来保持图像对齐,如下所示:

/* use a flexbox column to keep the longer titles under control */

.col-md-6 {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}


/* just using a quick grid to get 2 columns - not necessary for the above to work */

.row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20px;
}
<div class="row">
  <div class="col-md-6">
    <h2>This Heading takes up One line</h2>
    <img src="#">
  </div>

  <div class="col-md-6">
    <h2>This Heading takes 2 lines and pushes the image below down, throwing off vertical alignment with the image next to it.</h2>
    <img src="#">
  </div>

  <div class="col-md-6">
    <h2>A title that's not quite as long by maybe 2 lines</h2>
    <img src="#">
  </div>

  <div class="col-md-6">
    <h2>Yet another title</h2>
    <img src="#">
  </div>

</div>

希望这可以帮助您进一步前进。祝你好运,编码愉快!


推荐阅读