CSS 简记

251 阅读2分钟
1. flex 布局内容超出盒子宽度

解决flex布局内容超出盒⼦宽度问题

.content {
    flex: 1;
    width: 0
}
.content {
    flex: 1;
    overflow: hidden;
}
.content > * {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
  1. 因为设置了 nowrap,⽂字会将 content 撑开,导致内容超出了屏幕
  2. 上面的解决方案会动态的获得⽗容器的剩余宽度,且不会被⾃⼰的⼦元素把内容撑开。
2. flex 布局内容省略展示
<div class="content">
    <div class="dynamic">
        <div class="box">
            <span></span>
            <span></span>
        </div>
    </div>
    <div class="stable">
        <span></span>
    </div>
</div>
.content {
    display: flex;
    width: 100%;
}
.dynamic {
    flex-basis: content;
    min-width: 120px;
    margin-right: 40px;
}
.dynamic .box {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.stable {
    flex-shrink: 0;  //不被压缩   
}

flex-basis 指定了 flex 元素在主轴方向上的初始大小。

3. input自动变宽
const Demo = () => {
    const [value, setValue] = useState()

    const handleInputChange = (e) => {
        setValue(e.target.value)
    }

    return (<>
        <div className="box">
            <span>{value}</span>
            <input class="input" placeholder="" onChange={handleInputChange}/>
        </div>
    </>)
}
export default Demo;
.box {    
    position: relative;
    display: inline-block;
    min-width:90px;
    padding: 0;
}

.box span {
    display: inline-block;
    height: 100%;
}

.box .input {
    position: absolute;
    display: inline-block;
    left: 0;
    width: 100%;
    height: 100%;
    padding: 0;
    opacity: 1;
    min-width: 90px;
}

思路:使用 span 撑开父容器,input 随父容器宽度变化。

4. 清除 a 标签或者 span 标签之间的默认留白间距

css span字体间距,如何清除a标签或者span标签之间的默认留白间距

<div>
    <a>哈哈</a>
    <span>嘿嘿</span>
</div>
  1. 父元素设置 font-size:0,子元素设置具体的 font-size 值
div {
    font-zize: 0;
}

a, span {
    font-size: 14px;
}
  1. float浮动
a, span {
    float: left;
    display: block;
}

📢 letter-spacing同一行书写 的方式存在顶部间隙。

5. justify-self 失效

# justify-self 在 Flexbox 布局中失效

原因:在主轴上的元素是当成一组在操作。

解决方案:auto margins

.right {
    margin-left: auto;
}
6. 判断文本是否被省略
  • scrollWidth:包括由于 overflow 溢出而在屏幕上不可见的内容。
  • offsetWidth:一个典型的 offsetWidth 是测量包含
    • 元素的边框 (border)
    • 水平线上的内边距 (padding)
    • 竖直方向滚动条 (scrollbar)(如果存在的话)
    • CSS 设置的宽度 (width) 的值。
// jQuery
function isEllipsis(dom) {
    var checkDom = dom.cloneNode(), parent, flag;
    checkDom.style.width = dom.offsetWidth + 'px';
    checkDom.style.height = dom.offsetHeight + 'px';
    checkDom.style.overflow = 'auto';
    checkDom.style.position = 'absolute';
    checkDom.style.zIndex = -1;
    checkDom.style.opacity = 0;
    checkDom.style.whiteSpace = "nowrap";
    checkDom.innerHTML = dom.innerHTML;

    parent = dom.parentNode;
    parent.appendChild(checkDom);
    flag = checkDom.scrollWidth > checkDom.offsetWidth;
    parent.removeChild(checkDom);
    return flag;
};