Is there a way to get the vertical padding/margin to be the same as the auto horizontal margin?

Viewed 52

I want to set my element to be horizontally centered, and do such with

margin-left: auto;
margin-right: auto;

Now I want my vertical offset to be the same as my horizontal offset, except that it caps it out at a certain point, let's say 100px.

My current solution is using calc and min and adding it to the padding:

div {
    --width: 80ch;
    max-width: var(--width);
    /* short hand for margin-[left|right] */
    margin-inline: auto;
    /* short hand for padding-[bottom|top] */
    padding-block: min(100px, calc((100% - var(--width) / 2));
}

This works, and achieves the result I want. Which again, is that I have the same horizontal and vertical offset, up until a point (100px). At that point the horizontal offset still grows as the page width grows, but the vertical offset is capped at 100px.

but I'm wondering if there's a more simple solution.

2 Answers

I asume that you want a same effect as

margin: auto;

because you want to center the content inside the div.

If this is what you actually trying to achieve, there are several ways to do it. I recomend using flex.

with just 3 lines of code:

display:flex;
justify-content:center;
align-items:center;

Without seeing your full markup and how you are using your CSS, what you have seems to be enough for what you explained you are trying to achieve.

Note however, that your calculation could yield a negative value, but it will not matter since you are using it on the padding-block attribute---so the negative padding value will just be ignored. It may be problematic on a margin-block attribute. Nevertheless, I'd add a max(value, 0) just to ensure it gets 0 as minimum padding-block value. Also, you are missing a closing parenthesis before the division operator.

div {
    --width: 100px;
    --max-vertical-offset: 100px;
    background-color: yellow;
    width: var(--width);
    margin-inline: auto;
    padding-block: min(var(--max-vertical-offset), max((100vh - var(--width)) / 2, 0px));
}
<div class="my-div">
  test
</div>

Related