css如何设置对齐


本文摘自PHP中文网,作者醉折花枝作酒筹,侵删。

设置方法:1、使用“margin:0px auto”语句设置水平对齐;2、使用position属性,配合top、bottom、left和right属性设置左或右对齐;3、使用“float:right|left”语句设置左或右对齐。

本教程操作环境:windows7系统、CSS3&&HTML5版、Dell G3电脑。

1、使用 margin 属性来水平对齐

可通过将左边距和右边距设置为“auto”来对齐元素。但前提是必须声明!DOCTYPE,否则在IE8是无效的。这样就可以居中元素了,例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>document</title>

<style>

div{

    margin: 0px auto;

    width: 70%;

    height: 300px;

    background-color: red;

}

</style>

</head>

<body>

<div></div>

</body>

</html>

YZS$ZAI$9RR(}27BL)`(N35.png

提示:如果宽度是 100%,则对齐没有效果。

2、使用 position 属性进行左和右对齐

使用这种方法在兼容性这一块无疑是最好的方法了,但当使用 position 属性时,请始终设置 !DOCTYPE 声明,在IE8 以及更早的版本存在一个问题。如果容器元素(在我们的案例中是 <div class="container">)设置了指定的宽度,并且省略了 !DOCTYPE 声明,那么 IE8 以及更早的版本会在右侧增加 17px 的外边距。例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>document</title>

<style>

body{

    margin: 0;

    padding: 0;

}

.container{

    position: relative;

    width: 100%;

}

.right{

    position: absolute;

    right: 0px;

    width: 300px;

    height: 50px;

    background-color: red;

}

</style>

</head>

<body>

<div class="container">

    <div class="right"></div>

</div>

</body>

</html>

3、使用 float 属性来进行左和右对齐

当使用 float 属性时,IE8 以及更早的版本存在一个问题。如果省略 !DOCTYPE 声明,那么 IE8 以及更早的版本会在右侧增加 17px 的外边距。这似乎是为滚动条预留的空间。当使用 float 属性时,请始终设置 !DOCTYPE 声明:例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>document</title>

<style>

body{

    margin: 0;

    padding: 0;

}

 

.right{

    float: right;

    width: 300px;

    height: 50px;

    background-color: red;

}

</style>

</head>

<body>

<div class="container">

    <div class="right"></div>

</div>

</body>

</html>

VSGEFU[[}6B(H@B6J`_TAKJ.png

推荐学习:css视频教程

以上就是css如何设置对齐的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

css怎么设置表格线

几种关于html和css的使用方法

css中border是什么意思

css哪个样式不推荐使用

css实现滚动阴影效果的小技巧(分享)

css选择器学习之聊聊复合选择器(详细介绍)

css怎么设置平行虚线

怎么在css中改变光标样式

css怎么实现下边框阴影效果

css样式表常驻留在文档的什么区域中

更多相关阅读请进入《css》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...