DEV Community

Cover image for Center Stuff using VSCode
Sobhan Dash
Sobhan Dash

Posted on • Updated on

Center Stuff using VSCode

Now I know for sure when coding for long hours for after a long gap we all go to Stack overflow to search one thing(even though it's just 3 lines of code) and that is "how to center x".

Being a fun banter in a recent interview I gave, on how to center a div. I thought if it is that simple, why not simplify it even more. Writing the same piece of code or copy-pasting is still a hassle xD.

So, while trying to find some solution I came across an interesting idea. Why not use VSCode Snippet to do it?
I confess I did not know that we can set custom snippets before this.

So How do we do it?

For beginners who don't use code snippets, VSCode allows us to define a block of code that can be inserted with the help of a certain letter or set of letters and a TAB hit.

On Windows: Go to File then to Preferences then to User Snippets

On Mac: Replace File with Code menu -> Preferences -> User Snippets

Getting to User Snippets

This will open a popup box will open asking which file you want to edit. Click on the css.json.

In the file, write the following code block:

"Center Things" : {
  "prefix": "fc",
  "body": [
    "align-items: center;",
    "justify-content: center;"
  ],
  "description": "Center items in a flex container"
}
Enter fullscreen mode Exit fullscreen mode

Inside css.json

The prefix is the text you'll have to write before hitting the TAB to expand the body. fc stands for "flex center".

We can make multiple such snippets. Here's one including the display: flex option

"Flex and Center Things" : {
  "prefix": "ffc",
  "body": [
    "display: flex;",
    "align-items: center;",
    "justify-content: center;"
  ],
  "description": "Define a container flex and center it"
}
Enter fullscreen mode Exit fullscreen mode

Save the file and have fun with it!

Example 2

Although this article is focused on VSCode, I'm sure there must be similar settings and files in other code editors as well.

What do you think of this? Let me know in the comments👇🏻

Follow my Twitter and LinkedIn.

Top comments (0)