关于居中问题

  近期做移动端项目,某一个页面内每个模块都有按钮,按钮大小一样,离底部距离一样,于是写了公共样式,在这里遇到个问题——居中,因为有时候是2个按钮,有时候是一个,整体宽度不一致,于是用了最基本的方法,给最外层position:fixed;bottom:20px;left:50%;margin-left:-容器宽度的一半。这样问题是解决了,但是不怎么灵活,宽度改变了我的margin-left值就要变,很繁琐。

  后来经尝试+朋友指点,终于得以解决,具体如下:

  HTML代码:

1 <div class="ui_Btn">
2     <div>跳过</div>
3     <div>配置wifi</div>
4 </div>

  CSS代码:

 .ui_Btn {width: 100%;text-align: center;position: fixed;bottom: 10%;left:0;}/* fixed也可以用absolute代替,根据页面需求调整*/
 .ui_Btn div {width: 120px;height: 40px;line-height: 40px;text-align: center;border-radius: 10px;
        display: inline-block;border: 1px solid #26AD60; background: #26AD60;color: #fff;}

这个方式针对固定在底部的按钮比较适用,如果是文档中的按钮,取消position,bottom,left即可。只是其中的道理还不明白,望各路大神指点。

 

div垂直居中,知道高度的情况下:

<style>
    .wrap{
        width: 500px;height: 500px;border: 1px solid #000000;
        display: table-cell;vertical-align: middle;text-align: center;
    }
    .wrap div{
        width: 100px;height: 100px;background: red;display: inline-block;
    }
</style>
<body>
   <div class="wrap">
       <div></div>
  </div> </body>

 div垂直居中,不设置高度:

<style>
    .mark{
        width: 100%;height: 100%;position: fixed;background: rgba(0,0,0,.5);top: 0;left: 0;z-index: 1;
    }
    .content{
        width: 85%;position: fixed;left: 50%;top: 50%;background: #fff;transform: translate(-50%,-50%); text-align: center;z-index: 9;
    }
    p{
        padding: .5rem;
    }
</style>

<body>
    <div class="outer">
        <div class="mark"></div>
        <div class="content">
            <p>测试居中</p>
        </div>
    </div>
</body>
transform: translate(-50%,-50%);是关键
posted @ 2016-04-06 11:45  背对太阳的向日葵  Views(182)  Comments(0Edit  收藏  举报