share

How to Vertically Center a Button with CSS

May 17, 2018 | Code Snippets, Dev / Code, UX & Web Design

how to vertically center a css button

When it comes to horizontally centering an element, it’s usually not that difficult (knock on wood).

Vertically centering elements can at times become challenging, leaving the user to guess what value to set for line-height which is never really that accurate.

I’m going to show you a few ways to center elements vertically depending on the positioning.

First, we’ll go through a scenario in which the element is positioned statically, this is the default positioning for any css element and is what an element is positioned if no other value is specified.


Vertically Aligning a Button with CSS Using Flex


In a container set to display: flex, any elements in that container will size themselves relative to other flex-positioned elements using the flex-grow property.

For instance, in the above snippet, try setting the two elements inside the container to different flex-grow values and see how they size themselves accordingly.

Note that flex-direction tells the browser that this element will size itself according to the height of the container.

No matter the size of the container, this element will stay positioned vertically so long as the respective display properties are in place.


Centering a Fixed Button Vertically with CSS


#element {
    position:fixed;
    top: 50%;
   -ms-transform: translateY(-50%);
   -webkit-transform: translateY(-50%);
   -moz-transform: translateY(-50%);
   -o-transform: tranlslateY(-50%);
    transform: translateY(-50%);
}

This is a very simple way of centering an element with respect to a browser windows height for a centered element. Note this works for elements positioned absolute as well.

Try and use the flex value in your own way by experimenting with it until you get get a good idea of what it does.

This often comes in handy.

Contact us if you’d like another demonstration, or you can visit our code snippets gallery or web development blog posts.

Share This Article

related articles

some sponsors

Haven’t signed up for our newsletter?

Be a lot cooler if ya did


We send nothing but the good shit. Once a week. That’s it.

Be a lot cooler if ya did

UX and Web Design blog articles
Web Development & Coding blog articles
Lifestyle blog articles
Branding blog articles
Graphic design blog articles
Software reviews blog articles

Time's up, let's do this

Stay up-to-date with all of the design and creative news, resources, and inspiration by signing up for the CreativesFeed newsletter!