我想在段落的侧面设置按钮,使其与该段落中的元素垂直对齐:
<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中的特定元素对齐?
这与仅垂直对齐两列有所不同,因为文本段落断点与右侧的按钮出现无关。
答案 0 :(得分:2)
您可以使用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>