Center the absolute positioned content
.center{
top : 50%;
left : 50%;
transform : translate(-50%,-50%);
}
Codepen: https://codepen.io/3sanket3/pen/LYYOWwV
Maintain aspect ratio of the container
.container{
padding-bottom:56.4%; /* aspect ratio 16:9*/
}
The percentage should be calculated as: 16:9(w:h) = h*100/w => 56.25%. Similarly,
- 1:1 => 100%
- 4:3 => 75%
Codepen: https://codepen.io/3sanket3/pen/dyyZWMX
Truncate the text
.truncate{
display:block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Codepen : https://codepen.io/3sanket3/pen/OJJOmqB
Set width as the available rest of the space
It is useful when you have two adjacent containers. One has a fixed width and the other one should adjust according to the available remaining space.
.fix-width-container{
float: left;
width: 200px;
}
.adjustable-container{
width: calc(100%-200px);
}
Using CSS Variable
// 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
Preserve line breaks in the preview
It is useful when we want to show a preview of the content user entered in let say <textarea>
.preview{
white-space: pre-line;
}
CSS is something, which has no ends of learning. I would love to learn if you have such interesting snippets or links.
Icon Courtesy: https://thenounproject.com/term/css/60411/
Top comments (7)
I usually use
margin: auto
to center the content in the middle.Does it work even for the absolute content? I tried but doesn't seems working. Any codepen or something to refer?
Sorry, my bad. I was thinking all the moment in relative position. Your code is useful in absolute position, sure!
Very handy ... Thanks...
Very helpful to avoid the same stackoverflow searches. Thanks!
You should put each one as a separate blog post on your blog so that it can be searched via Google and devs can get exactly what they're looking for.
True, thanks for the suggestion. But do you think content is enough to be a separate blog post?