【问题标题】:How do I absolute position a div from left to the right using media queries?如何使用媒体查询从左到右绝对定位 div?
【发布时间】:2016-01-06 12:15:24
【问题描述】:

我在使用媒体查询将 div 定位到右侧时遇到问题。

HTML

<div class="container">
  <div class="left"></div>
</div>

CSS

body,html { height:100%; }

.container {
  width:1000px;
  height:100%;
  background:#eee;
  position:relative;
}

.left {
  height:100%;
  width:200px;
  background:orange;
  position:absolute;
  left:0;
}

@media only screen and (max-width: 700px) {
  .left {
    position:absolute !important;
    right:0 !important;
   }
 }

左侧 div 绝对位于左侧。当我的媒体查询以 700px 宽度触发时,我希望将同一个 div 绝对定位在右侧。

问题是它不会这样做!我尝试使用!重要。我试图重申媒体查询中的立场。没有!

奇怪的是,如果我从 div 绝对定位在右侧开始,而对于媒体查询,则将 div 绝对定位在左侧。有用! 什么?为什么?

DIV 绝对位于左侧,通过媒体查询将 DIV 置于右侧。
不工作

http://jsfiddle.net/zfdmmyaz/

DIV 绝对位于右侧,使用媒体查询将 DIV 置于左侧。
这工作

http://jsfiddle.net/md07a02t/

如何让它工作?触发媒体查询时,如何让绝对左侧的 div 将自己绝对定位到右侧?

【问题讨论】:

    标签: css responsive-design media-queries


    【解决方案1】:

    使用浮动而不是左。此外,您不需要将 .left div 设为绝对值,因为它将绝对定​​位到它的相对容器。

    HTML

    <div class="container">
      <div class="left">Content</div>
      <div class="clear"></div>
    </div>
    

    CSS

    body,html { height:100%; }
    
    .container {
      width:1000px;
      height:100%;
      background-color:#eee;
      position:relative;
      border: 1px #000000 solid;
    }
    
    .left {
      height:100%;
      width:200px;
      background-color:orange;
      float: left;
    }
    
    .clear {
        clear:both;
    }
    
    @media only screen and (max-width: 700px) {
        .container {
            width:100%;
        }
    
        .left {
            float: right !important;
        }
     }
    

    【讨论】:

    • 感谢您的选择。我尝试在我的模板上使用浮点数,它也可以工作。它确实会占用空间,因为它会移动我的 div 以为该 div 腾出空间。我需要一些在模板上不移动任何东西的东西。谢谢!
    【解决方案2】:

    您需要将left 的值重置为auto,然后设置right 的值。

    jsfiddle

    @media only screen and (max-width: 700px) {
        .left {
            position: absolute;
            left: auto;
            right: 0;
            background: lime;
        }
    }
    

    【讨论】:

    • 谢谢!那行得通!你能解释一下为什么会这样吗?为什么如果我从绝对右侧开始,我可以毫无问题地使用媒体查询一直绝对定位到左侧,反之则不行?
    • 您只能设置左侧或右侧(顶部或底部),但不能同时设置两者,除非您希望元素拉伸其宽度/高度以覆盖整个相关容器左右。
    • 快速demo 显示设置所有值时发生的时间:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2014-05-21
    相关资源
    最近更新 更多