0

I know there's another question like this but I tried it and the answer didn't work.

I have a p with a div and I want to be able to use a reverse (negative) margin on the p. At the moment it's not effecting the p but the containing div.

Here's the code :

.reset {
    margin-left:4px;
    margin-top: 4px;
    height:50px;
    width:50px;
    background:#FFF;
}
.reset p {
    margin-top:-4px;
    font-size: 38px;
    font-family: sans-serif;
    text-align: center;
}

Thanks in advance

4

2 回答 2

1

I am not sure of your whole solution, but setting the div to relative, and the <p> to absolute should get you in the right direction. Here is a fiddle to play with.

 .reset {
        margin-left:4px;
        margin-top: 4px;
        height:50px;
        width:50px;
        background:Silver;
        position: relative;

    }
    .reset p {
        position:absolute;
        margin-top:-4px;
        font-size: 38px;
        font-family: sans-serif;
        text-align: center;
    }

[UPDATE]

A comment in another answer(now deleted) mentions that negative margins are not valid css. To work with this, change the .reset p to:

.reset p {
    position:absolute;
    top: -4px; //or whatever you want
    left: 0px;  //or whatever you want
    font-size: 38px;
    font-family: sans-serif;
    text-align: center;
}
于 2013-01-31T17:00:41.403 回答
1

It doesn't work because your p is the first element of your div. As a result, the margin-top of both your p and div are somewhat merged.

For example, if you put margin-top: 20px on both your p and your div, it will only result in a 20px top margin, not 40px.

The easiest way is to use position: relative;:

p { position: relative; top: -4px; }

This way, the p is still in the usual flow, but you move it 4px up.

于 2013-01-31T17:14:05.700 回答