【半转半写】div水平垂直居中的完美解决方案
来源:互联网 发布:2016年中国m2数据 编辑:程序博客网 时间:2024/06/06 03:38
使用margin-left:auto;margin-right:auto; 可以让你的div居中对齐。
.style{margin-left:auto;margin-right:auto;}
缩写形式为:
.style{margin:0 auto;}
数字0 表示上下边距是0。可以按照需要设置成不同的值。
查看下面的例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>居中div演示效果</title>
<style type="text/css">
.align-center{
margin:0 auto; /* 居中 这个是必须的,,其它的属性非必须 */
width:500px; /* 给个宽度 顶到浏览器的两边就看不出居中效果了 */
background:red; /* 背景色 */
text-align:center; /* 文字等内容居中 */
}
</style>
</head>
<body>
<div class="align-center">居中div演示效果</div>
</body>
</html>
注意,需要加上上面的那句
才能生效,要是不想要这句的话,也可以给body加一个属性:
body{text-align:center;}
另外,让div内的内容(包括文字及图片)居中的代码是: text-align:center;
div居中的完美解决方案! (水平垂直居中)
1,关于居中使用css为:position:fixed;left:50%;top:50%;margin-left:width/2;margin-top:height/2;
对于ie6,只能把position:改成absolute;
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>水平垂直居中div演示效果</title>
<style type="text/css">
.align-center{
position:fixed;left:50%;top:50%;margin-left:width/2;margin-top:height/2;border:1px solid red;
}
</style>
</head>
<body>
<div class="align-center">水平垂直居中div演示效果</div>
</body>
</html>
也可以用js实现水平垂直居中,即代码:
<script>
$(window).resize();
$(function () {
$(window).resize(function(){
ChangeWebWH();
});
});
function ChangeWebWH () {
$(".main").css({
position: "absolute",
top: ($(document.body).height() - $(".main").outerHeight()) / 2,
left: ($(document.body).width() - $(".main").outerWidth()) / 2
});
}
</script>
<body class="main" style="width:400px;height:400px;border:1px solid red;"></body>
resize方法:当调整浏览器窗口的大小时,发生 resize 事件。
如果需要跟随浏览器窗口的大小进行调整,则需要运用到onresize方法触发,则:
<script>
$(window).resize();
$(function () {
$(window).resize(function(){
ChangeWebWH();
});
});
function ChangeWebWH () {
$(".main").css({
position: "absolute",
top: ($(document.body).height() - $(".main").outerHeight()) / 2,
left: ($(document.body).width() - $(".main").outerWidth()) / 2
});
}
</script>
<body class="main" onresize="ChangeWebWH();" style="width:400px;height:400px;border:1px solid red;"></body>
- 【半转半写】div水平垂直居中的完美解决方案
- div+css 水平居中和垂直居中的多种解决方案
- 完美DIV、图片水平垂直居中
- div水平垂直居中
- DIV 水平垂直居中
- div 水平垂直居中
- div水平垂直居中
- div垂直水平居中
- div水平垂直居中
- div水平垂直居中
- div水平垂直居中
- div水平垂直居中
- DIV水平垂直居中
- div 水平居中 垂直居中
- DIV水平居中、垂直居中
- div垂直居中 水平居中
- DIV水平居中、垂直居中
- css div的水平、垂直同时居中
- Java Web读取properties配置文件
- scheme的应用序
- Java并发编程:CountDownLatch、CyclicBarrier和Semaphore
- windows下常见cmd命令
- leetcode14
- 【半转半写】div水平垂直居中的完美解决方案
- 让Winform控件同时支持单击和双击事件
- C中.h头文件的写法
- oracle 12c 安装
- Android M 新的运行时权限开发者需要知道的一切
- jQuery EasyUI使用教程之创建一个拖放的购物车
- Python查询天气预报
- 使用百度地图API
- 网络攻击知识之几种IP地址攻击方式