user2953119
user2953119

Reputation:

Centering div block relative to this center

I want to set the gemoetrical center of my div block at the geometrical center of the screen. How i can do that? Let we have

<div style="position: absolute; width: 240px; height: 150px; margin:50%; >
    some content
</div>

But it doesn't work. I dont undestand why it doesnt. margin:50% equivalent to margin-top/left/right/bottom: 50%. Thus we have extra space to our div element as 50% of linear screen size. Why it is neccesary to define the width and height explicitly if we use margin attribute or top/left/right/bottom attributes?

Upvotes: 0

Views: 111

Answers (3)

Nitesh
Nitesh

Reputation: 15779

Use the below to make it centralized.

For Instance,

<div style="display: table; margin: 0px auto;">
    <div style="margin: 0px auto; text-align: center; background: none repeat scroll 0% 0% gray; width: 240px; height: 150px; display: table-cell; vertical-align: middle;">
        some content
    </div>
</div>

WORKING DEMO

Hope this helps.

Upvotes: 0

user2953119
user2953119

Reputation:

We can use the following:

<div style="position: absolute; margin: auto; width: 240px; height: 150px; top: 0; left: 0; bottom: 0; right: 0;">
    some content
</div>

Upvotes: 0

Almir Filho
Almir Filho

Reputation: 4677

Here we go. The HTML:

<body>
    <div class="centered">Hello</div>
</body>

The CSS:

.centered {
    position: absolute;
    width: 240px; 
    height: 150px;
    /* positioning the element (top/left corner) at the center */
    top: 50%;
    left: 50%;
    /* moving the element's center to the screen's center (compensating relatively to the dimensions) */
    margin-top: -75px; /* half of the height */
    margin-left: -120px; /* half of the width */
}

margin: 50% won't work because of elements with position: absolute lose the reference to the parent's dimensions. This is one of the various layout problems with the CSS Box Model.

However, you can use the Flexbox Layout Model, that would be a lot easier:

body {
    display: flex;
}

.centered {
    margin: auto;
}

You just need to set margin: auto and the parent element must be set as display: flex. Simple =)

Upvotes: 1

Related Questions