1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 清除浮动的方法总结CSS实现水平垂直居中方法总结

清除浮动的方法总结CSS实现水平垂直居中方法总结

时间:2021-07-21 09:15:44

相关推荐

清除浮动的方法总结CSS实现水平垂直居中方法总结

1、清除浮动的方法总结

当容器的高度为auto,且容器的内容中有浮动(float为left或right)的元素,在这种情况下,容器的高度不能自动伸长以适应内容的高度,使得内容溢出到容器外面而影响(甚至破坏)布局的现象。这个现象叫浮动溢出,为了防止这个现象的出现,就需要清楚浮动。

清楚浮动的方法:

①:定义父级div的高度。

②:添加一个空div,利用css提供的clear:both清除浮动,让父级div能自动获取到高度

dom:

<div class="div1"><div class="floatLeft"></div><div class="floatRight"></div><div class="clearFloat"></div></div>

css:

.clearFloat{clear: both;}

③:在通过伪类清除浮动

dom:

<div class="div1 clear"><div class="floatLeft"></div><div class="floatRight"></div></div>

css:

.clear:after{display:block;content:””;visibility:hidden;clear:both;height:0}.clear{zoom:1}/*针对IE6、7*/

④:父级div定义overflow:hidden

原理:overflow:hidden属性相当于是让父级紧贴内容,必须定义width或zoom:1,同时不能定义height,使用overflow:hidden时,浏览器会自动检查浮动区域的高度(缺:不能和psition配合使用,超出的尺寸会被隐藏)

2、CSS实现水平垂直居中方法总结

dom结构:

<body><div class="big"><div class="mid"></div></div></body>

以下为实现.mid在.big里居中的方法:

(一)利用绝对定位+transform(.mid宽高可不固定)

.big{position: relative;width: 500px;height: 400px;background: #faebcc;}.mid{position: absolute;top: 50%;left: 50%;transform: translate3d(-50%, -50%, 0);}

(二)利用绝对定位+margin(.mid宽高固定)

.big{position: relative;width: 500px;height: 400px;background: #faebcc;}.mid{position: absolute;top: 50%;left: 50%;width: 100px;height: 80px;margin: -40px 0 0 -50px;/*负值取宽、高的一半*/}

(三)利用定位与margin:auto(.mid宽高固定)

.big{position: relative;width: 500px;height: 400px;background: #faebcc;}.mid{position: absolute; width: 100px;height: 80px;top: 0;right: 0;bottom: 0;left: 0;margin: auto;}

(四)利用display:table-cell(.mid宽高固定)

CSS中有一个用于竖直居中的属性vertical-align,但只有当父元素为td或者th时,这个vertical-align属性

才会生效,对于其他块级元素,例如div、p等,默认情况下是不支持vertical-align属性的,设置块级元素的

display类型为table-cell,激活vertical-align属性,但display:table-cell存在兼容性问题,

所以这种方法没办法跨浏览器兼容。

.big{display: table-cell;vertical-align: middle;/*垂直*/text-align: center;/*水平*/width: 500px;height: 400px;background: #faebcc;}.mid{display: inline-block;width: 100px;height: 80px;background: greenyellow;}

(五)使用flex布局(.min宽高可不固定)

.big{display: flex;align-items: center;justify-content: center;width: 500px;height: 400px;background: #faebcc;}.mid {width: 100px;height: 80px;background: greenyellow;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。