对于PC和mobile 水平垂直居中适配
2016-03-30 15:25
489 查看
div{
width: 500px;
height: 400px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -200px;
background-color: black;
}
对于PC的一个DIV居中应该是没什么问题的
这样就居中了
但是如果要适配移动端的话,这个div可能就会显得比较大,一般情况下左右两边会超出屏幕。
最好的办法应该把width设为100%,这样就能适配各种的分辨率。
所以我做了以下更改
div{
width: 100%;
max-width: 500px;
height: 400px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -200px;
background-color: black;
}
貌似这样就可以解决问题了
但问题又来了,当页面的宽度小于500px的时候,比如400px,却要向左移动250px,按照left:50%来算应该从200开始减去250,所以是-50px
所以适配又出了问题
那么我们要怎么做呢?
这个时候我突然想到margin: 0 auto;可以水平居中但不能垂直居中。
然后就把这段代码放了上去。
怎么调都没办法居中。
然后突然想到一个解决方法:
使用position: relative;和
margin: 0 auto;相结合来做
html,body{
width: 100%;
height: 100%;
}
div{
width: 100%;
max-width: 500px;
height: 400px;
margin: 0 auto;
position: relative;
top: 50%;
margin-top: -200px;
background-color: black;
}这样就适配移动和PC的所有分辨率了!
width: 500px;
height: 400px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -200px;
background-color: black;
}
对于PC的一个DIV居中应该是没什么问题的
这样就居中了
但是如果要适配移动端的话,这个div可能就会显得比较大,一般情况下左右两边会超出屏幕。
最好的办法应该把width设为100%,这样就能适配各种的分辨率。
所以我做了以下更改
div{
width: 100%;
max-width: 500px;
height: 400px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -200px;
background-color: black;
}
貌似这样就可以解决问题了
但问题又来了,当页面的宽度小于500px的时候,比如400px,却要向左移动250px,按照left:50%来算应该从200开始减去250,所以是-50px
所以适配又出了问题
那么我们要怎么做呢?
这个时候我突然想到margin: 0 auto;可以水平居中但不能垂直居中。
然后就把这段代码放了上去。
怎么调都没办法居中。
然后突然想到一个解决方法:
使用position: relative;和
margin: 0 auto;相结合来做
html,body{
width: 100%;
height: 100%;
}
div{
width: 100%;
max-width: 500px;
height: 400px;
margin: 0 auto;
position: relative;
top: 50%;
margin-top: -200px;
background-color: black;
}这样就适配移动和PC的所有分辨率了!
相关文章推荐
- [转载]Activity中ConfigChanges属性的用法
- CSS3属性教程与案例分享
- CSS3属性教程与案例分享
- CSS3的calc()使用
- 使用CSS3的appearance属性改变元素的外观
- CSS3美化图片
- CSS3质感分析——表面线性渐变
- 分析选项卡底部内凹圆角制作
- 细说百度图片栏目——图片展示效果
- 8个实用的响应式设计框架
- 20+ Animation Scripts, Libraries and Plugins
- 在Windows 8.1的IE 11中屏蔽双击放大功能
- html5 web数据存储
- SEO
- 异步流程控制:7 行代码学会 co 模块
- [译] React 入门
- Apple官网研究之使用Justify布局导航
- 如何优雅处理前端异常?