【问题标题】:How to center some element on web page on all browsers and devices?如何在所有浏览器和设备的网页上居中某些元素?
【发布时间】:2015-01-12 05:11:42
【问题描述】:

我有一些元素、div 或任何带有 id 的元素,我想将它放在网页上。 但是当它在电脑屏幕上看起来不错时,它在手机上看起来很糟糕。 如何正确地居中它,使用任何框架,如引导程序或其他东西,或者没有任何方法,jquery 也是可能的。 它在所有移动设备和所有计算机浏览器上也看起来不错。 谢谢。

【问题讨论】:

标签: javascript jquery html css cross-browser


【解决方案1】:

我会给你另一种解决方案来定位绝对中心(水平和垂直),它永远不会失败并且适用于我测试过的每个浏览器(即 8+)。

你有 HTML

<div id="centered">
   <!-- Place your content here -->
</div>

这是 绝对中心(水平和垂直)的 CSS

#centered{
  width: 500px;
  height: 500px;
  position:absolute;
  top:0;
  right:0;
  bottom:0;
  left:0;
  margin:auto;
}

如果您只想要垂直

#centered{
  width: 500px;
  height: 500px;
  position:absolute;
  right:0;
  left:0;
  margin:auto;
}

而且只有水平的

#centered{
  width: 500px;
  height: 500px;
  position:absolute;
  top:0;
  bottom:0;
  margin:auto;
}

【讨论】:

    【解决方案2】:

    这很简单。 HTML

    <div id="container">
       <div id="content">
         Your content here. It can be text, image or anything.
       </div>
    </div>
    

    CSS

    #container{
      width:auto;
      height: auto;
    }
    
    #content{
    width:90%
    height:90%;
    margin:auto;
    }
    

    注意: 边距自动实际上使对齐居中,有时它取决于场景。在有固定高度和宽度的地方,它更容易。祝你好运

    提示 如果你想看到 的对齐方式,你应该在设计的时候在 CSS 中使用#selector{border:solid}; ,然后你可以删除它..

    【讨论】:

      【解决方案3】:

      试试这个:

      <div class="center">
       <p>.........content...........</p>
      </div>
      

      现在的 CSS:

      .center{
       margin:0 auto; 
       width:500px; /*adjust your width*/
      }
      

      【讨论】:

        【解决方案4】:

        CSS

         .flexme{
              display: -webkit-box;
              display: -moz-box;
              display: -ms-flexbox;
              display: -webkit-flex;
              display: flex;
            }     
        

        HTML

         <div class = 'flexme' style = 'position:absolute; top:0; bottom:0; right:0; left:0; '>
              <div id = 'div_you_want_centered' style = 'margin:auto;'> 
                   This will be Centered 
              </div>
         </div>
        

        查看http://css-tricks.com/snippets/css/a-guide-to-flexbox/

        第一个 div 占据了整个屏幕,并为每个浏览器设置了 display:flex。第二个 div(居中的 div)利用了 display:flex div,其中 margin:auto 效果很好。

        注意 IE11+(IE10 带前缀)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-06-26
          • 2015-07-17
          • 2013-06-28
          • 1970-01-01
          • 2017-04-04
          • 2010-09-28
          相关资源
          最近更新 更多