【问题标题】:How to align one div inside a container and another one align to the right end of browser window?如何在容器内对齐一个 div,另一个与浏览器窗口的右端对齐?
【发布时间】:2018-10-04 04:42:18
【问题描述】:

我在一个容器中有 2 个 div,我想将一个 div 设置为与容器左对齐,另一个设置为通过 css 与浏览器的右端对齐。这可能吗?

Example Image

有人帮我解决这个问题吗?

.container {
  background: #ccc;
  height: 400px;
  max-width: 500px;
  margin:0 auto;
}

.outer {
  background: #f8f9fa;
  margin-top: 40px;
}

.left-box {
  background: #000;
  color: #fff;
  padding: 10px 0;
  float:left;
  width:50%;
  margin-top:20px;
  height:100px;
}

.right-box {
  background: #EC8400;
  padding: 10px 0;
  float:right;
  margin-top:20px;
  width:50%;
  height:100px;
}
<div class="container">
  <div class="outer">
    <div class="left-box">
      some text
    </div>
    <div class="right-box">
      text/image here
    </div>
  </div>
</div>

【问题讨论】:

  • 这取决于您的要求。当页面或容器滚动时会发生什么?是否有任何 div 必须保持锁定在其位置? div可以有固定的宽度吗?
  • 这是一个正常的页面,不需要锁定在它的位置。请参阅小提琴jsfiddle.net/ys5mvjt6/1 一些问题,(图像截止/滚动条可见。)我期望的是,右侧图像需要调整为窗口大小。

标签: html css browser alignment containers


【解决方案1】:

您可以使用固定位置,然后将左 0 用于要左对齐的 div,将 0 用于要右对齐的 div。 CSS会是这样的

.divleft {
    position: fixed;
    left: 0;
}

.divright {
    position: fixed;
    right: 0;
}

【讨论】:

    【解决方案2】:

    是的, 先把你想要的 div 放在浏览器的右边容器外面,因为它在 div 里确实没有意义,但是如果你想把它放在容器里,它仍然是可能的。

    试试这个

    // if the right-box is outside the container
    .right-box
    {
    position: absolute;
    right : 0;
    }
    
    
    // if the right-box is inside the container
    .right-box
    {
    position: absolute;
    left : 100%;
    }
    

    注意:第二个从容器的最右侧开始右框,可以根据自己的喜好进行调整。

    左框类似

    【讨论】:

    • 谢谢,响应中的一些问题(图像截断/滚动条可见),jsfiddle.net/ys5mvjt6/1
    • 确保您的所有父元素都正确包含您的子元素,例如删除浮动属性或将overflow : none 添加到父元素还将width :100% 添加到您的图像以适合其父元素的容器。 . 这是一个线索如何处理你的代码jsfiddle.net/ys5mvjt6/1/…
    • 您也可以使用本站w3schools.com获取更多信息
    • 我被检查过,没有浮动和溢出。并且只有容器已修复,图像也是 100% 宽度,但仍然是同样的问题。 jsfiddle.net/ys5mvjt6/3
    • 你能具体告诉我问题是什么,你到底想要什么???删除重叠添加 *{overflow:hidden;} 到你的 css 如果你想要滚动添加 overflow:scroll 到容器之外,我认为没有问题
    猜你喜欢
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 2022-01-26
    • 2015-09-05
    • 2021-12-18
    相关资源
    最近更新 更多