Home > OS >  How to set left and right CSS properties without setting top and bottom
How to set left and right CSS properties without setting top and bottom

Time:09-30

Is there any way to set just left and right (of margins, padding, border-width, etc.) to the same value without setting the top and bottom at all, in one expression, rather than...

.my-class-name { 
  margin-left: 2px; 
  margin-right: 2px;
}

For properties, if I want the left and right to the same value and my top and bottom to some other value, I can do something like

.my-class-name { margin: 3px 2px; }  

But to set only the left and right margins, I had thought that there might be a keyword in the vein of unset or inherit that might be a "unspecified" setting that might let me do something like

.my-class-name { margin: unspecified 2px; }

And thus let other earlier CSS take hold on the same selector. But none of the keywords seem to do this, unless I'm missing something. I'd also like to know how to do top-and-bottom without left or right, similarly.

So is there a way? Or would you need some superset of CSS like Sass to do so?

CodePudding user response:

Yes, by using margin-inline or margin-block

.box { 
  margin-inline: 10px; /* left and right */
  
  width:50px;
  height:50px;
  display:inline-block;
  background:red;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Those properties are called "Flow-relative properties" and they apply to padding, border and more: https://drafts.csswg.org/css-logical/

You don't have to worry about the support as it's pretty good: https://caniuse.com/mdn-css_properties_margin-inline

Related:

What is the difference between margin-block-start and margin-top?

Is there a css function that allows me to set the values of top, right, bottom, and left for position all in one line?

  •  Tags:  
  • css
  • Related