I would like to achieve a layout that looks like this:
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With