【问题标题】:Vertically aligning the text of the left div depending on the position of the right div根据右div的位置垂直对齐左div的文本
【发布时间】:2018-09-19 01:32:30
【问题描述】:

好的,我有两个平行的 div 框,都包含文本。 div 框没有固定宽度,它会按百分比变化。现在左侧 div 框中的文本应该从右侧框中一个标题的相同位置开始,我不知道如何垂直对齐它们。

#left {
	width: 19%;
	height: auto;
	margin-left: auto;
	background-color: green;
	float: left;
	margin-left: 20%;
	text-align: right;
	padding-bottom: 20px;
	padding-top: 10px;
}

#right {
	float: left;
	width: 38%;
	height: auto;
	background-color: blue;
	margin-left: 1%;
	text-align: left;
	padding-bottom: 20px;
	padding-left: 1%;
	padding-right: 1%;
	padding-top: 10px;
}
<html>
<head>
</head>
<body>
<div id="wrapper">

  <div id="left">
    <p>This text should be at the same position as the caption "here"</p>
<p>There are also images involved, this should be at the same position as the caption "here2"</p>
  </div>

  <div id="right">

    <p>Words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words. </p>

    <h1>here</h1> 

    <p>Words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words. </p>
 <h1>here2</h1> 

    <p>Words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words words. </p>

  </div>

</div>
</body>
</html>

最后应该是这样的: Example 1

它也应该适用于一些图像:

Example 2

如果有人能够回答我的问题,我将非常高兴,或者如果无法做到这一点,请告诉我。

【问题讨论】:

  • 我认为你需要 Javascript 来实现这个
  • 好的,我看看我能找到什么,谢谢:)

标签: html css


【解决方案1】:

第一个图像示例可以使用 javascript 实现 - 只需计算右侧框的高度,移除左侧框的高度并除以 2 即可获得垂直对齐左侧框所需的上边距 - 或,试试这个 CSS:

html, body {
  width: 100%;
  height: 100%;
}

#wrapper {
  position: relative;
  width: 100%;
}
#left {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);

  width: 19%;
  height: auto;
  margin-left: auto;
  background-color: green;

  margin-left: 20%;
  text-align: right;
  padding-bottom: 20px;
  padding-top: 10px;
}

#right {
  float: right;
  margin-right: 20%;

  width: 38%;
  height: auto;

  background-color: blue;
  margin-left: 1%;
  text-align: left;
  padding-bottom: 20px;
  padding-left: 1%;
  padding-right: 1%;
  padding-top: 10px;
}

不过,我建议看一下 bootstrap 以构建更复杂的布局 - 尤其是示例 2。它提供了一些强大的布局选项:

https://getbootstrap.com/docs/4.1/layout/grid/

【讨论】:

  • 太棒了 :) 我的解决方案是否按预期解决了您的问题?
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 2012-12-09
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 2017-01-17
相关资源
最近更新 更多