我最近学到的一些很棒的 CSS 代码片段:将绝对定位的内容居中;保持容器的纵横比;截断文本;将宽度设置为剩余可用空间;在预览中保留换行符

2025-06-04

我最近学到的一些很棒的 CSS 代码片段

将绝对定位的内容居中

保持容器的纵横比

截断文本

将宽度设置为剩余可用空间

在预览中保留换行符

将绝对定位的内容居中

.center{
  top : 50%;
  left : 50%;
  transform : translate(-50%,-50%);
}

Codepen:https://codepen.io/3sanket3/pen/LYYOWwV

保持容器的纵横比

.container{
  padding-bottom:56.4%; /* aspect ratio 16:9*/
}

百分比应计算为:16:9(w:h) = h*100/w => 56.25%。同样,

  • 1:1 => 100%
  • 4:3 => 75%

Codepen:https://codepen.io/3sanket3/pen/dyyZWMX

截断文本

.truncate{
  display:block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Codepen:https://codepen.io/3sanket3/pen/OJJOmqB

将宽度设置为剩余可用空间

当你有两个相邻的容器时,它很有用。一个容器具有固定宽度,另一个容器应根据可用的剩余空间进行调整。

.fix-width-container{
  float: left;
  width: 200px;
}
.adjustable-container{
  width: calc(100%-200px);
}

使用 CSS 变量

// Declaring variable at root level, you can set it at common parent level
:root{
  --left-pane-width : 200px; 
}

.fix-width-container{
  float: left;
  width: var(--left-pane-width);
}

.adjustable-container{
  width: calc(100%-var(--left-pane-width));
}

Codepen:https://codepen.io/3sanket3/pen/qBBVjgy

在预览中保留换行符

当我们想要显示用户输入内容的预览时,它很有用<textarea>

.preview{
  white-space: pre-line;
}

CSS 真是学无止境。如果你有这么有趣的代码片段或链接,我很乐意学习。

图标来源:https://thenounproject.com/term/css/60411/

文章来源:https://dev.to/3sanket3/few-awesome-css-snippets-i-recently-learned-33pb
PREV
GitHub vs GitLab Git GitHub GitLab GitLab vs GitHub- 细微功能 -> 哦!现在到了我们胜出的时候了
NEXT
热门 CSS 框架