Left margin of Margin: auto-ed elements = to padding left of 100%-width overflow item

后端 未结 1 889
伪装坚强ぢ
伪装坚强ぢ 2021-01-24 04:19

Let me demonstrate the problem with the following HTML:

相关标签:
1条回答
  • 2021-01-24 05:06

    calc() method

    This can be done with the (experimental) calc property:

    div article {
        margin-left: calc(50% - 300px/2);
    }
    

    Demo

    Here you'd have to enter the width of the <header> (in this case 300px) and it will automatically determine what 50% - (width) / 2 is. This won't automatically change if you change the style for the <header> though, and it is not supported in too many browsers.

    margin-left and left method

    This is a method that would work in every modern browser: defining a left positioning, and then a negative left margin:

    div article {
        position:relative;
        left: 50%;
        margin-left: -150px;
    }
    

    Demo

    This first moves the element to 50% width on the page, and then moves it 150px to the left via its negative margin. You will have to enter the width of the <header>, like the calc() method, but here you'll have to divide it by 2 yourself (shouldn't be too hard :P)

    0 讨论(0)
提交回复
热议问题