CSS选择器——伪元素选择器之处理父元素高度及外边距溢出

1. 子元素浮动导致父元素高度不够

问题描述:最小高度为100px的父元素,嵌套一个300px高度的子元素,当子元素浮动时,父元素高度并不随之升高。
问题视图:
clipboard.png
期望视图:
clipboard.png

待解决代码:

<!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;}

已解决代码:

<!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>

2.子元素浮动导致外边距溢出

问题描述:
在某些特殊的条件下,为子元素设置上外边距时,有可能会作用到父元素上。
问题视图:
clipboard.png
期望视图:
clipboard.png

待解决代码:

<!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;}
已解决代码:

<!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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值