volter9
volter9

Reputation: 735

How to centerize overflowed container with padding?

I need to centerize overflowed container (div or section) that has padding and it's inside of body. Container is fixed width (500 pixels in example) and padding 100 pixels horizontally. How could I centerize this container?

I tried following:

#wrapper {
    text-align: center;

    margin: 0px auto;
    padding: 0px 100px;
    width: 500px;
}

http://jsfiddle.net/Volter9/tu6yg5ch/

If you will change width of result tab less than 700 pixels, you would see that container isn't properly centerized.

Thank you for attention!

Upvotes: 1

Views: 142

Answers (1)

Marc Audet
Marc Audet

Reputation: 46825

This may be one way of doing it. You need to use positioning with either position: relative or position: absolute.

The type of positioning to use will depend on other aspects of the layout, for example, if you have other elements after the wrapper, any fixed heights for the wrapper and so on.

body {
    overflow-x: hidden;
}

#wrapper {
    text-align: center;
    border: 1px dotted black;
    margin: 0px auto;
    padding: 0px 100px;
    width: 700px;
    position: relative;
    left: 50%;
    margin-left: -350px;
    box-sizing: border-box;
}
<div id="wrapper">
    content
</div>

Note: The border-box property is not strictly necessary. The margin-left value needs to be half of the total width of the wrapper element, so you need to do the math right to the computed width of the wrapper block.

Upvotes: 1

Related Questions