【问题标题】:Vertically align two elements if one is in variable width wrapper [duplicate]如果两个元素在可变宽度包装器中,则垂直对齐两个元素[重复]
【发布时间】:2018-12-25 17:51:07
【问题描述】:

我希望在段落的一侧有按钮,与该段落中的元素垂直对齐:

<div style="width:20%">
  This is an example text. This is an example text. This is an example text. This is 
  an example text. This is an <span>A</span> <button>Aligned with A</button> example text. This is an example text. 
  This is an example text. This <span>B</span> <button>Aligned with B</button> is an example text. This is an example 
  text. This is an example text. This is an example text. This <span>C</span><button>Aligned with C</button> is an
  example text. This is an example text. 
</div>

在这个例子中,我想让一个按钮与文本中的每个元素垂直对齐。我无法将垂直位置设置为固定,因为它们在文本中的行数随包装器 div 的实际宽度而变化,并且我不能使用 display: table 因为我不想在文本段落中换行。输出应如下所示:

由于包装器 div 的宽度由浏览器决定,我不知道换行的位置,因此不知道文本的垂直对齐方式。有没有办法将按钮与 div 中的特定元素对齐?

这与仅垂直对齐两列不同,因为文本段落断点独立于右侧按钮的出现。

【问题讨论】:

  • 为什么要重复和否决?如果有不清楚的地方,请要求澄清@connexo
  • 按钮的已知宽度是否相同?如果是这样,您可以将它们 floatright,然后通过负 margin-right 移动越过容器的右边缘
  • 按钮的宽度已知,如何将按钮后的内容移动到右边的容器中,你能提供代码吗?
  • 请看这个小提琴:jsfiddle.net/n8sd479r(希望我理解正确)
  • 这个问题在这里似乎比建议的“重复”更相关:stackoverflow.com/q/48504231/2533215

标签: html css


【解决方案1】:

您可以使用 display:table 属性并使您的 div 的行为类似于 HTML 表格。 请参阅文档https://www.w3schools.com/cssref/pr_class_display.asp

并使用vertical-align 对齐您的项目。

.paragraph-wrap {
  display: table;
}
.paragraph {
  display:table-row;
}
.paragraph > *{
  display:table-cell;
  vertical-align: middle;
}
<div class="paragraph-wrap">
  <div class="paragraph">
    <p>This is an example text.</p>
    <span><button>Button</button></span>
  </div>
  <div class="paragraph">
    <p>This is an example text.  This is an example text. This is an example text. This is an example text.</p>
    <span><button>Button</button></span>
  </div>
  <div class="paragraph">
    <p>This is an example text.</p>
    <span><button>Button</button></span>
  </div>
  <div class="paragraph">
    <p>This is an example text.</p>
    <span><button>Button</button></span>
  </div>
</div>

【讨论】:

  • 这几乎可以工作,除了换行符。有没有办法在不开始新行的情况下开始新段落,就像我的图形一样?
  • 是的,只需用div 包裹你的段落,例如:&lt;div class="paragraph"&gt; &lt;div&gt;&lt;p&gt;[...]&lt;/p&gt;&lt;p&gt;[...]&lt;/p&gt;&lt;p&gt;[...]&lt;/p&gt;&lt;p&gt;[...]&lt;/p&gt;&lt;p&gt;[...]&lt;/p&gt;&lt;/div&gt; &lt;span&gt;[...]&lt;/span&gt; &lt;/div&gt;
  • 我的意思是两个
    之间没有换行符,因此段落换行中的文本没有换行符,就像在我的示例图形中一样,知道该怎么做吗?
  • 我已经更新了我的问题以使其更清楚
  • 你在哪里插入按钮?请更新您的 html 代码。
猜你喜欢
相关资源
最近更新 更多
热门标签