'How to set only vertical padding?

Sometimes I would like to set top and bottom padding explicitly on an element but leave left and right padding to the unchanged browser default. I know I can write

.myElement { padding-top: 20px; }
.myElement { padding-bottom: 20px; }

but this way I need to repeat both the selector .myElement and the length value twice - or rather copy and paste the whole line and switch left with right. I was hoping to find something less redundant, so I tried to use padding with two values and replace the second length with inherit. That's not good CSS, I know, it was an attempt, but it doesn't work either (sets horizontal padding to 0):

.myElement { padding: 20px inherit; }

See here: http://jsfiddle.net/185ty3yp/

Any advice how to do it better?



Solution 1:[1]

These days you can do it like this:

.myElement { padding-block: 20px; }

Browser support

Solution 2:[2]

#ul1, #ul2{
  padding:20px 0; /* top and bottom 20px, left and right 0 */
}

http://www.w3schools.com/css/css_padding.asp

you can only set padding to either a fixed length or a percent, no other values I'm afraid

Solution 3:[3]

I understand one of the reasons for finding vertical padding might be wanting just to change one place in future modification. If so, we can try:

.element{
    --title-vertical-padding: 20px;
    padding-top: var(--title-vertical-padding);
    padding-bottom: var(--title-vertical-padding);
}

Solution 4:[4]

you can use padding-block property to set vertical padding and padding-inline to set horizontal padding.

padding-block: 20px; /*vertical padding */
padding-inline: 20px; /*horizontal padding*/

The same goes for margin, use margin-block to set vertical margin and margin-inline to set horizontal margin.

margin-inline: auto; can be used to center a div.

Solution 5:[5]

try this code DEMO

#ul1, #ul2 {
    background-color: cyan;
    padding-top: 20px;
    padding-bottom: 20px;
}

#ul2 {
    background-color: yellow;
}

Solution 6:[6]

You can try like this

padding: 20px 50px 75px 100px;

//top padding is 20px
//right padding is 50px
//bottom padding is 75px
//left padding is 100px

In your case you can apply like this if it is common for any ul

ul
{
  padding-top: 20px;
  padding-bottom: 20px;
}

any specific places you can override this css.

check Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam Taylor
Solution 2 Gho
Solution 3 Ian 1989
Solution 4 Suraj Rao
Solution 5 Alex Wilson
Solution 6