问题描述:最小高度为100px的父元素,嵌套一个300px高度的子元素,当子元素浮动时,父元素高度并不随之升高。
问题视图:
![]()
指望视图:
![]()
待解决代码:css
<!DOCTYPE html> <html> <head> <title>1</title> <meta charset="utf-8"> <style type="text/css"> .d0{width: 300px;background: #336;min-height: 100px;} .d1{float: right;width: 200px;background: #289;height: 200px;opacity: 0.5} </style> </head> <body> <div class="d0"> <div class="d1">我是浮动的子元素</div> </div> </body> </html>
解决方案:父元素底部追加一个内容为空的子元素,class为clear,对其添加样式.clear:after{content:"";display:block;clear:both;}html
已解决代码:spa
<!DOCTYPE html> <html> <head> <title>1</title> <meta charset="utf-8"> <style type="text/css"> .d0{width: 300px;background: #336;min-height: 100px;} .d1{float: right;width: 200px;background: #289;height: 200px;opacity: 0.5} /*解决问题的代码*/ .clear:after{content:"";display:block;clear:both;} </style> </head> <body> <div class="d0"> <div class="d1">我是浮动的子元素</div> <div class="clear"></div> </div> </body> </html>
问题描述:
在某些特殊的条件下,为子元素设置上外边距时,有可能会做用到父元素上。
问题视图:
![]()
指望视图:
![]()
待解决代码:3d
<!DOCTYPE html> <html> <head> <title>2</title> <meta charset="utf-8"> <style type="text/css"> .d1{width: 300px;height: 100px;background: #336} .d2{width: 300px;height: 100px;background: #289} .d2son{width: 150px;height: 50px;background: #caa;opacity: 0.5;margin-top: 50px;} </style> </head> <body> <div class="d1">上面的div</div> <div class="d2"> <div class="d2son">下面的div的子元素</div> </div> </body> </html>
解决方案:
在d2中的第一个子元素位置处(!!!必须是空子元素)生成内容为空显示方式为table(!!!必须是table元素)
d2中添加第一个子元素,对其添加样式:.d2:before {content:"";display:table;}
已解决代码:code
<!DOCTYPE html> <html> <head> <title>2</title> <meta charset="utf-8"> <style type="text/css"> .d1{width: 300px;height: 100px;background: #336} .d2{width: 300px;height: 100px;background: #289} .d2son{width: 150px;height: 50px;background: #caa;opacity: 0.5;margin-top: 50px;} /*解决问题的代码*/ .d2:before {content:"";display:table;} </style> </head> <body> <div class="d1">上面的div</div> <div class="d2"> <div class="d2son">下面的div的子元素</div> </div> </body> </html>