Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically aligning CSS :before and :after content [duplicate]

People also ask

How do you vertically align content in CSS?

Use the CSS line-height property Add the line-height property to the element containing a text larger than its font size. By default, equal spaces will be added above and below the text, and you'll get a vertically centered text.

How do I vertically align two items in a div?

To align two <div> elements vertically in Bootstrap 3, you can try using the CSS Flexible Box Layout. In the example below, we display the needed row as a flex container box with the CSS display property and then, align the flex-items (columns) vertically with the align-items property.

Which of the following are true about CSS property vertical-align?

It sets the vertical alignment of an the entire webpage. Answer: It sets the vertical alignment of an element.

How do you align block elements vertically?

When the element to be centered is an inline element we use text-align center on its parent. When the element is a block level element we give it a width and set the left and right margins to a value of auto. With text-align: center in mind, most people look first to vertical-align in order to center things vertically.


Answered my own question after reading your advice on the vertical-align CSS attribute. Thanks for the tip!

.pdf:before {
    padding: 0 5px 0 0;
    content: url(../img/icon/pdf_small.png);
    vertical-align: -50%;
}

I'm no CSS expert, but what happens if you put vertical-align: middle; into your .pdf:before directive?


You can also use tables to accomplish this, like:

.pdf {
  display: table;
}
.pdf:before {
  display: table-cell;
  vertical-align: middle;
}

Here is an example: https://jsfiddle.net/ar9fadd0/2/

EDIT: You can also use flex to accomplish this:

.pdf {
  display: flex;
}
.pdf:before {
  display: flex;
  align-items: center;
}

Here is an example: https://jsfiddle.net/ctqk0xq1/1/


I think a cleaner approach is to inherit the vertical alignment:

In html:

<div class="shortcut"><a href="#">Download</a></div>

And in css:

.shortcut {
    vertical-align: middle;
}
.shortcut > a:after {
    vertical-align: inherit;
{

This way the icon will align properly in any resolution/font-size combination. Great for use with icon fonts.


Using flexboxes did the trick for me:

.pdf:before {
    display: flex;
    align-items: center;
    justify-content: center;
}