清除浮动的方法总结CSS实现水平垂直居中方法总结
生活随笔
收集整理的這篇文章主要介紹了
清除浮动的方法总结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;}?
?
總結
以上是生活随笔為你收集整理的清除浮动的方法总结CSS实现水平垂直居中方法总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CSDN博客启用
- 下一篇: 灰蒙蒙的天空心情说说128个