css 怎么实现 div水平居中 呢?

html-css092

css 怎么实现 div水平居中 呢?,第1张

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

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

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

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

.tl {

width: 240px

height: 193px

position: absolute/*这里一定要设置*/

z-index: 999999/*这里是该元素与显示屏的距离,据说越大越好,因为没有它也是可以的*/

margin-top: 20%

margin-left: -209px

background-image :url("/ship_three/images/tl.png")

-webkit-transition: .5s ease-in-out/* css的transition允许css的属性值在一定的时间内从一个状态平滑的过渡到另一个状态 */

-moz-transition: .5s ease-in-out/*这里为了兼容其他浏览器*/

-o-transition: .5s ease-in-out

background-image: url("/ship_three/images/tl.png")

}

可以,没问题CSS代码就是上面的。

扩展资料:

div中style使用css代码

div中可以直接写CSS样式代码,只需要DIV代码(标签)中使用style属性即可直接写CSS样式。

DIV代码:

<div style="color:#F00border:1px solid #000width:300pxheight:100px">你好 DIVCSS5</div> 

完整案例代码与效果截图:

完整HTML案例代码

<!DOCTYPE html>

<html>

<head>

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

<title>DIV直接写CSS DIVCSS5案例</title>

</head>

<body>

<div style="color:#F00border:1px solid #000width:300pxheight:100px">你好 DIVCSS5</div>

</body>

</html>

div标签内常用属性列表

1、style 设置css样式(扩展了解style标签)

2、align 设置div盒子内的内容居中、居左、居右

3、id 引人外部对应#(井号)选择符号样式

4、class 引人外部对应.(句号)选择符号样式

5、title 设置div(标题)鼠标经过时显示文字(扩展了解 title标签)

参考资料来源:DIV-百度百科

案例一、对margin上下设置为0 - TOP

<</span>html>

<</span>head>

<</span>meta charset="utf-8" />

<</span>title>p行距实例 在线演示 DIVCSS5</</span>title>

<</span>style>

p{ line-height:20px}

.divcss5-a p{ margin:0 auto}

</</span>style>

</</span>head>

<</span>body>

<</span>div class="divcss5-a">

<</span>p>第一段</</span>p>

<</span>p>第二段<</span>br />第二段第二行</</span>p>

<</span>p>第三段</</span>p>

</</span>div>

</</span>body>

</</span>html>

设置margin-top为0,margin-bottom为0

案例二、对margin上下设置为30px - TOP

<</span>html>

<</span>head>

<</span>meta charset="utf-8" />

<</span>title>p行距实例 在线演示 DIVCSS5</</span>title>

<</span>style>

p{ line-height:20px}

.divcss5-b p{ margin:30px auto}

</</span>style>

</</span>head>

<</span>body><</span>div class="divcss5-b">

<</span>p>第一段</</span>p>

<</span>p>第二段<</span>br />第二段第二行</</span>p>

<</span>p>第三段</</span>p>

</</span>div>

</</span>body>

</</span>html>

这里对对象".divcss5-b"设置了CSS margin:30px auto相当于设置margin-top为30px、margin-bottom为30px

案例三、对margin上下设置为0,padding上下为20px - TOP

<</span>html>

<</span>head>

<</span>meta charset="utf-8" />

<</span>title>p行距实例 在线演示 DIVCSS5</</span>title>

<</span>style>

p{ line-height:20px}

.divcss5-c p{ margin:0 autopadding:20px 0}

</</span>style>

</</span>head>

<</span>body>

<</span>div class="divcss5-c">

<</span>p>第一段</</span>p>

<</span>p>第二段<</span>br />第二段第二行</</span>p>

<</span>p>第三段</</span>p>

</</span>div>

</</span>body>

</</span>html>

以上设置了margin-top和margin-bottom均为0,然后我们设置padding-top和padding-bottom值为20px。