Martin Gottweis Martin Gottweis - 1 year ago 78
CSS Question

Set margin-left and margin-right and keep vertical margin

Is there any way to set horizontal margin and inherit the vertical margin? Other way than to set

? I hoped for something like
margin: inherit 20px;
to work.

Check it out here:


<div class="outer">
<div class="inner horizontal-margin-working">
Working but lame
<div class="inner horizontal-margin-notworking">
Not working

Css: .outer {
background: #27ae60;
padding: 10px;

.inner {
margin: 10px;

.horizontal-margin-working {
margin-left: 50px;
margin-right: 50px;

.horizontal-margin-notworking {
margin: inherit 50px;

Answer Source

No, there is no way to keep the vertical margins when using the short-hand property. That is because:

  • In CSS, when two or more selectors are applicable for an element, the values that are provided in the latest selector (or more specific selector) wins for common properties. Here, margin is given both in .inner, the other class selector and so the one within .inner will get overwritten.
  • inherit (along with a length value) doesn't seem to be valid for the shorthand margin property whereas it is valid for the longhand margin-* properties and when inherit alone is specified in the shorthand. Moreover, margin: 10px is set in the .inner selector which is actually the same element (and not the parent), so inherit won't work.
  • auto is a valid value for margin but it does not keep the margin specified in a previous selector. It tells the UA to calculate and assign a suitable value. For your case, it may set the margin-top and margin-bottom to 10px but it may not also (depending on other factors).
  • When any length value (pixel or percentage) is given for the margin property, the UA decides on how to interpret the given value based on the no. of values provided. If one value is provided, that gets set to all sides, 2 values means first is vertical while second is horizontal margin and so on.

So, in short, overriding the margin-left and margin-right specifically (like in .horizontal-margin-working) is the only way you can get to keep the vertical margin.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download