盒子实现水平居中
有兴趣的可以看我的github地址:https://github.com/wangzhichao2019/-web-
- ①text-align:center;可以实现盒子里面的内容(文字,行内元素,行内块元素)居中对齐
- ②margin:0 auto;表示的是盒子的左右是auto(自动)的,距离上边框的距离是0
- ③margin-left:auto;表示盒子整体左边区域充满,盒子整体效果是在右边
- ④margin-right:auto;表示盒子右边区域自动充满,盒子紧靠左边(和浏览器默认界面是一样的)
- ⑤在盒子里面不更改样式的话,盒子里面的内容是和浏览器一样宽的
一、笔记:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>2019年9月7日</title>
<style>
div
{
text-align:center;/
width: 300px;
height: 100px;
background-color: pink;/*现在可以看到文字依然是居中的,但是盒子并不是居中的*/
margin: 0 auto;
padding-top: 100px;
/*margin-left: auto; margin-right:auto;*/
/*
所以,水平居中的另一种实现方法是将上面的两种都写上:
margin-left:auto;
margin-right:auto;
也就是意味着左右两侧都自动充满,所以最后盒子的实现效果是居中对齐,而且距上边的距离不限于0
(所以让一个盒子水平居中,最重要的就是让盒子的左右auto就好了margin:100 auto;也能实现)
*/
/* margin:auto;表示上下左右都是auto,但是由于上下并没有效果,左移最后也能实现盒子整体的居中对齐*/
}
</style>
</head>
<body>
<div>
<!--123 在默认条件下,是和浏览器一样宽的-->
我们认识一周了
</div>
</body>
</html>
二、作业:自己瞎捣鼓的(用三种方式来实现盒子的水平居中)
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>盒子水平居中三种方法的实现作业!</title>
<style>
div
{
text-align:center;
width = 300px;
}
.nav
{
background-color:red;
margin: 0 auto;
}
.b
{
background-color: yellow;
margin-left: auto;
margin-right: auto;
}
.c
{
background-color: green;
margin: auto;
}
</style>
</head>
<body>
<div class="nav">
这是实现盒子水平居中的第一种方式
</div>
</br>
<div class="b">
这是实现盒子水平居中的第二种方式
</div>
</br>
<div class="c">
这是实现盒子水平居中的第三种方式
</div>
</body>
</html>
截图的效果是这样的: