admin 管理员组

文章数量: 1087139


2024年2月25日发(作者:php编程工作)

CSS网页布局DIV水平居中的各种方法

容器中的内容居中:text-align: center

容器在上层容器中居中:margin-right: auto; margin-left: auto;

1. margin:auto 0 与 text-aligh:center

在现代浏览器(如Internet Explorer 7、Firefox、Opera等)现代浏览器实现水平居中的方法很简单,只要设定到左右两侧的空白为自动即可。意即:

#wrap { margin:0 auto;}

上面这段代码的意思是说使wrap这个div到左右两侧的距离自动设置,上下为0(可以为任意)。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"/TR/xhtml1/DTD/">

<html xmlns="/1999/xhtml">

<head>

<title> new document </title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style type="text/css">

div#wrap {

width:760px;

margin:0 auto;

border:1px solid #333;

background-color:#ccc;

}

</style>

</head>

<body>

<div id="wrap">

在Firefox等现代浏览器设定页面元素的水平居中,只要指定margin:0 auto;即可

<pre>

div#wrap {

width:760px;

margin:0 auto; /*这里的0可以任意值*/

border:1px solid #ccc;

background-color:#999;

}

</pre>

</div>

</body>

</html>

但是这在Internet Explorer 6及改正的版本中是不起作用的,在Internet Explorer中text-align属性是可继承的,即在父元素中设置后在子元素中就默认具有了该属性。因此我们可以在body标签中设置text-align属性值为center,这样页面内所有的元素都会自动居中,同时我

们还要加一个hook把页面中的文字变成我们习惯的阅读方式——居左对齐。因此我们要如此来写代码:

body {text-align:center;}

#wrap {text-align:left;}

这样在Internet Explorer中我们就轻松实现了Div的居中对齐。因此要在所有的浏览器中显示居中的效果,我们就可以这样写我们的代码:

body { text-align:center; }

#wrap { text-align:left;

margin:0 auto; }

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

"/TR/xhtml1/DTD/">

<html xmlns="/1999/xhtml">

<head>

<title> CSS+Div实现水平居中对齐的页面布局 </title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style type="text/css">

body { text-align:center; }

div#wrap {

text-align:left;

width:760px;

margin:0 auto;

border:1px solid #333;

background-color:#ccc;

}

Transitional//EN"

</style>

</head>

<body>

<div id="wrap">

2.相对定位与负的边距

对于wrap进行相对定位,然后使用负的边距抵消偏移量。这种方法比较简单还很容易实现:

#wrap {

position:relative;

width:760px;

left:50%;

margin-left:-380px

}

这段代码的意思是,设置wrap的定位是相对于其父元素body标签的,然后将其左边框移动到页面的正中间(也就是left:50%含意);最后我们再从中间位置向左偏移回一半的距离来,这样就实现了水平居中了。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"/TR/xhtml1/DTD/">

<html xmlns="/1999/xhtml">

<head>

<title> CSS+Div实现水平居中对齐的页面布局 </title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style type="text/css">

div#wrap {

position:relative;

width:760px;

left:50%;

margin-left:-380px;

border:1px solid #333;

background-color:#ccc;

}

</style>

</head>

<body>

<div id="wrap">

在所有浏览器中都有效的方法:

<pre>

div#wrap {

position:relative;

width:760px;

left:50%;

margin-left:-380px;

border:1px solid #333;

background-color:#ccc;

}

</pre>

</div>

</body>

</html>

同样,在设定水平居中前你需要设定一个固定的宽度。


本文标签: 居中 水平 页面 元素 设置