Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position a div with equal margins for left, right, and top

Tags:

html

css

I would like to achieve a layout that looks like this:

Inner div nested in Outer div with equal margins for top, left, and right.

I am interested in a css/html only solution, so no javascript required.

The widths of both divs are dynamic, so I cannot use any static margins.

The spacing between the sides of the divs, and the top, should be the same.

I tried using margin: auto auto 0 auto on the inner div, as you can see in this jsfiddle, but it only works for left and right.

like image 948
V Maharajh Avatar asked Apr 29 '15 23:04

V Maharajh


People also ask

How do you make the margin-left and right equal?

You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

Can we align an element by setting margin-left and margin right?

Block elements can be aligned by setting the left and right margins to "align” with the margin: auto; property we can align the block level elements into the centre. block-level element occupies the entire space of its parent element.

How do you make a div sit side by side?

The most common way to place two divs side by side is by using inline-block css property. The inline-block property on the parent placed the two divs side by side and as this is inline-block the text-align feature worked here just like an inline element does.


1 Answers

Note, the following attempt doesn't answer the question fully, since the width of the child cannot be dynamic.

The idea is to use a percentage width + percentage margin-top values on the child. It's a responsive layout, see the comments in the code, and try it out on different window sizes.

JSFiddle: http://jsfiddle.net/jkoycs6e/

body {
    margin: 0;
}
.outer {
    height: 100vh; /*for demo only*/
    background: teal;
    overflow: auto;
}
.inner {
    width: 80%;
    background: gold;
    margin: auto;
    margin-top: 10%; /* 100%-80%/2 */
}
<div class="outer">
    <div class="inner">
        hello<br/>hello<br/>hello
    </div>
</div>
like image 159
Stickers Avatar answered Nov 10 '22 02:11

Stickers