【问题标题】:Aligning two elements from different divs对齐来自不同 div 的两个元素
【发布时间】:2021-12-07 06:40:12
【问题描述】:

在我的实习中,我被要求将网站上的按钮与旁边的文本对齐,但按钮和文本位于两个不同的 div 中。 Paint Mock

  • 代码在多个地方使用
  • 图片定义了容器的高度
  • 图像和文本的长度和高度并不总是相同

我的解决方案使用 jQuery 来计算按钮位置,但我不得不选择。由于图像高度,用于“窗口加载”而不是“文档就绪”。这会导致按钮在其他一切都解决后移动。这还可以,但并不完全令人满意。更改 html 会导致移动查看出现大量其他问题。

在窗口加载和文档准备好之间有什么东西吗?

是否有一些我不知道的 css hack?

或任何其他建议将不胜感激。

html:

<div class="body">
  <div class="container">
    <div class="first">
      <div class="text">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus ut, fuga perspiciatis minima ipsam est nam dignissimos, dolorum officia sit, molestias, nostrum culpa quaerat veniam minus. Repellat quibusdam, ducimus eum.
      </div>
    </div>
    <div class="second">
      <div class="image">
        <img src="https://picsum.photos/400" alt="">
      </div>
      <div class="button">
        <a href="google.com">
          My button
        </a>
      </div>
    </div>
  </div>
</div>

js:

$(window).load(function() {
    let button = $(".button");
  let divHeight = $(".first").outerHeight(true);
  let textHeight = $(".text").outerHeight(true);
  
  let top = divHeight / 2 + textHeight / 2;
    button.css("top", top);
})

css:

.body {
  width: 800px;
}

.container {
  display: flex;
  flex-direction: row;
  align-items: center;
  
  .first, .second {
    width: 50%;
  }
  
  .text {
    padding: 60px;
  }
  
}

.button {
  padding: 10px;
  background: lightblue;
  position: absolute;
  left: 740px;
  a {
    color: white;
  };
}

【问题讨论】:

  • 您能分享一下您目前正在尝试使用的代码吗?什么是 HTML?你的 JavaScript 是什么?没有代码,这只是要求我们在黑暗中拍摄并猜测您的 DOM 结构可能是什么。
  • 您能否在Minimal, Reproducible Example 中包含您的 HTML 标记和必要的 CSS + JS。它让我们更好地了解您想要实现的目标
  • 添加了我的代码的快速“小提琴”

标签: jquery sass twitter-bootstrap-3


【解决方案1】:

把整个东西放在main-containerdiv,然后使用flex。请参阅我在下面放置的示例。我希望这能回答你的问题。

.main-container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 200px;
  height: 80px;
  border: 1px solid gray;
}
<div class="main-container">
  <div>image here</div>
  <div>text here</div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-14
    • 2015-01-24
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多