Div居中在屏幕正中间

html-css019

Div居中在屏幕正中间,第1张

一、用margin负值,这种方法适合div的宽高固定。 position:absolute left:50% top:50% margin-left:-宽度的一半 margin-top:-高度的一半; 二、使用css3新属性translate,这个不需要固定宽高。 position:absolute left:50% top:50% transform:translate(-50% -50%) 三、使用flex布局,这个也不需要固定宽高。但是需要在父容器上面设置 display:flex justify-content:center align-items:center 四:将上下左右全设为0. position:absolute top:0 bottom:0 left:0 right:0 margin:auto 这样全部设为0后会拉伸图片充满父容器,然后margin设为auto会自动填充上外边距,就能实现居中。

主要css代码有两个:

1,text-align:center

2,margin:0 auto;

其两个样式需要配合使用才能实现div盒子的居中显示排版。

首先我们对body设置text-align:center,再对需要居中的div盒子设置css样式margin:0 auto,这样即可让对应div水平居中。

举个例子,居中代码为:

<!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">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />

<title>CSS使div居中制作</title>

<style>

body{ text-align:center}

#nav{ margin:0 autowidth:200pxheight:150pxborder:5px double #FF0066}

/* css注释:为了观察效果设置宽度  高度 边框等样式 */

</style>

</head>

<body>

<div id="nav">

DIV居中

</div>

</body>

</html>

为了观察div居中效果,我们对div设置一个div命名为“#div”在html中div标签内使用id=“nav”,设置其宽度为200px高度为150px,边框也设置了颜色。

效果如图:

以上就是CSS让DIV居中的方法。

因为“text-align:center”控制的是文本居中,div居中可以用外边距margin来实现。

1、新建html文件,在body标签中添加div标签,div标签中的内容为“演示文本”,添加题目中的css样式,为了方便演示,给div标签添加灰色背景,这时可以发现div靠近浏览器的左侧,文字在div中居中:

2、为div标签添加新的外边距“margin”属性,属性值为“0 auto”,“0”指的是上下外边距为0,“auto”指的是左右外边距为自适应:

3、这时无论浏览器的宽度是多少,div都会在浏览器上水平居中: