水平文字居中与盒子水平居中
- 文字居中是
text-align:center
,可以使文字,行内元素,行内块元素居中。 - 盒子元素居中
margin: 0 auto;
- 示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>居中</title> <style type="text/css"> span{ /*建立行内块元素 */ display: inline-block; } div{ width: 500px; /*盒子居中*/ margin: 0 auto; /*文字,行内元素,行内块元素居中*/ text-align: center; background-color: #ff9c9c; } </style> </head> <body> <div> <!--文字居中--> 1111 <!--行内元素居中--> <strong>2222</strong> <!--行内块元素居中--> <span>333</span> </div> </body> </html>
插入图片与背景图片
- 插入图片运用多一些,一般用于产品展示类的元素,位置呢只能靠盒模型的
padding
与margin
来设置 - 背景图片一般用于小图标(小图片)与整体背景布置(大图片),位置通过
background-position
来设置
清除默认边距
页内元素若不设置内外边距浏览器会给元素默认添加内外边距,为了清除默认的内外边距,我们通常用:
* {
padding:0;/*清除内边距*/
margin:0;/*清除外边距*/
}
TIP:为了兼容老版本浏览器,一般只设置左右内外边距,不设置上下内外边距。
外边距合并
用margin设置两个块元素的上下外边距后会出现外边距的合并
-
相邻元素垂直外边距合并
设置了两个上下相邻的元素,当上面的元素设置了下外边距,下面的元素设置了上外边距时,两个边距就会合并,取最大值。如下所示:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> *{ margin: 0; padding: 0; } .top{ background-color:red; width: 400px; height: 400px; /*上面的div的下外边距设置为100px*/ margin-bottom: 100px; } .bottom{ background-color: blue; width: 400px; height: 400px; /*下面的div的上边距设置为200px*/ margin-top: 200px; } </style> </head> <body> <div class="top"></div> <div class="bottom"></div> <!-- 最终外边距为两个外边距的最大值200px --> </body> </html>
解决方案:只给一个元素设置
margin
值 -
塌陷————嵌套块元素垂直外边距的合并(前)
发生塌陷的要素:
- 两个嵌套关系的元素
- 父元素没有设置上内边距及边框
- 都设置了上外边距
发生塌陷的现象:
- 两个上外边距发生合并
- 合并后的外边距为两个外边距的最大值
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> *{ margin: 0; padding: 0; } .father{ width: 500px; height: 500px; background-color: #ff0000; /*设置父元素的上边距为100px*/ margin-top: 100px; } .son{ width: 200px; height: 200px; background-color: rgba(255, 255, 255, 0.4); /*设置子元素的上边距为200px*/ margin-top: 200px; } </style> </head> <body> <!--父元素的外边距为200px,子元素与父元素的上边距为0px--> <div class="father"> <div class="son"></div> </div> </body> </html>
解决方案:
- 父元素设置上边框
- 父元素设置
padding-top:
- 父元素设置
overflow: hidden