hktir
hktir

Reputation: 99

Why won't my negative margins go above a certain area?

Here is the jsfiddle for reference: http://jsfiddle.net/4devvjyv/1/

I'm trying to get the "Section" box to go above the gray line so that it looks like the "Section" box is centered around the line. But negative margins are not pushing the box above the line.

.divider {
    margin-top: 6px;
    border-top: 2px solid gray;
    font-size: 10px;
    position: relative;
}

.divider-text {
    position: relative;
    border: 1px solid black;
    background-color: white;
    display: inline-block;
    padding: 0px 5px;
    margin-top: -200px;
}

The divider is the line, and the divider-text is the "Section" box. I put a margin-top of 6px for the divider just so I wouldn't mess up the spacing between the two content because I would like the "Section" box to be 6px above the line and 8px below the line.

Does anyone know why it's not working? I tried playing around with a negative left margin and the "Section" box behaved as it should.

Upvotes: 2

Views: 1881

Answers (1)

rob waminal
rob waminal

Reputation: 18429

Updated your jsfiddle

Use top: -20px instead of margin-top:-200px. I've use -20px because -200px will float way high and cannot be seen.

.divider-text {
    position: relative;
    border: 1px solid black;
    background-color: white;
    display: inline-block;
    padding: 0px 5px;
    top: -20px;
}

another solution would be

.divider-text {
    position: absolute;
    border: 1px solid black;
    background-color: white;
    display: inline-block;
    padding: 0px 5px;
    margin: -20px; // making it center.
}

releasing the element from it's parent element (position: absolute) will make the element float, does following the negative margin.

The element is still under its parent element so any floating styles will not go beyond its parent element unless you free it by, float, position:absolute, or display:block. But display block does not actually release the element from its parent but moves it to the next. -- need anyone's input on this though.

Upvotes: 3

Related Questions