代码之家  ›  专栏  ›  技术社区  ›  user2212461

如果两个元素之一位于可变宽度包装器中,则垂直对齐两个元素[重复]

  •  0
  • user2212461  · 技术社区  · 7 年前

    这个问题已经有了答案:

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

    <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>
    

    在本例中,我希望有一个按钮与文本中的每个元素垂直对齐。我无法设置固定的垂直位置,因为文本中的行数随包装器分区的实际宽度而变化,而且我不能使用display:table,因为我不希望文本段落中出现换行符。输出应该如下所示:

    illustration of how it should look like

    因为wrapper div的宽度是由浏览器决定的,所以我不知道行在哪里中断,因此也不知道文本的垂直对齐方式。是否有方法将按钮与DIV中的特定元素对齐?

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   caiovisk    7 年前

    您可以使用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>