这些常用的css你知道吗

355 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第7天,点击查看活动详情

1、清除浮动

主要为子元素浮动(float)之后,父元素无法撑起高度和宽度。


<style>   
    img {        
        float: left;    
    }    /* 清除浮动 */    
    .clear::after {      
        content: "";      
        display: block;      
        clear: both;    
    }
</style>

2、文字少时居中,多时靠左

但是要注意,当p的内容为英文单词组成的时候,如果单词过长,而不是“ pppppppppppppppppppppppppppppp”这样的一次,会被视为一个单位而造成超过div的尺寸。

如果你想要英文字符也有中文字符的效果的话,在p使用“ word-break:break-all”。

<div class="box">    <p class="content"></p></div>
<style>
    .box {      
        text-align: center;  
    }    
    .content {    
        display: inline-block;     
        text-align: left;  
    }
</style>


3、凹凸人

目的在于制造一个凹或凸的形状,利用了“ 2”。



<style>    
    .ao {        
        display: inline-block;        
        width: 0;   
    }    
    .ao::before {        
        content: "love 你 love";     
        outline: 2px solid #000;    
        color: #fff;    
    }
</style>

4、让padding,border不影响盒模型的大小

相信这点大部分人都知道,但是有一些奇怪的行为,比如说width <content + padding会怎样?实际上当padding + border> width时,元素的渲染大小(Chrome下)为padding + border;而padding + border <width时,允许剩余空间分配给content。


<style>  
    div {   
        box-sizing: border-box;  
    }
</style>
身高:100%占屏效果
<style>    
    html,body {    
        height: 100%;   
    }    
    div {   
        height: 100% 
    }
</style>

<style>    
    div {      
        position: absolute;  
        height: 100%;  
    }
</style>

5、任意高度元素展开

缺点是,如果高度太大会造成展开过快和重复中断,那么这个足够大的值应该适当。


<style>    
    div {    
        max-height: 0;    
        overflow: hidden;    
        transition: max-height .25s;   
    }  
    div.active {   
        max-height: 666px;  /* 需要足够大的值 */    
    }
</style>