user7663064
user7663064

Reputation:

why applying negative margin right doesn't work?

My Code:

.container {
    width: 100px;
    margin: 0 auto;
    padding: 0 10px;
    background: red;
}

/* this is inside the container */
.inside {
    width: 100%;
    height: 100px;
    background: blue;
    margin: 0 -10px;
}

outcome
expected outcome

What am I doing wrong? I've seen Bootstrap grid do something similar to this.

Quick update. sorry for poor explaining.further explaition:
margin: 0 -10px; is used to add margin to left and right but the right side doesn't do anything.

Upvotes: 3

Views: 2265

Answers (3)

Ivan86
Ivan86

Reputation: 5708

Use this to set the right margin:

margin:0 -10px 0 0;
    // top, right, bottom, left

Upvotes: 1

ArtOfCode
ArtOfCode

Reputation: 5712

The syntax for the CSS margin property is:

margin: (all|vertical horizontal|top right bottom left)(unit);

That means that your declaration of

margin: 0 -10px;

is using the vertical horizontal syntax - i.e. you're applying -10px margin to both sides of the element, not just the right. To fix this, use the full syntax:

margin: 0 -10px 0 0;

Upvotes: 2

Blazemonger
Blazemonger

Reputation: 92893

For .inside, width: 100% only covers the space inside the padding of the .container. You need to add the extra 20px back to its width:

.container {
  width: 100px;
  margin: 0 auto;
  padding: 0 10px;
  background: red;
}


/* this is inside the container */

.inside {
  width: calc(100% + 20px);
  height: 100px;
  background: blue;
  margin: 0 -10px;
}
<div class='container'>
  <div class='inside'></div>
</div>

Upvotes: 5

Related Questions