Do not fret if you have not yet mastered CSS layout - it has taken a while to become standardized and many current methods use clever workarounds to achieve the desired look, which may not always be intuitive.
By default, blocks stack vertically, but you may need them to flow horizontally for a specific section.
The preferred "modern CSS way" is to utilize flexbox, a tool designed specifically for layouts like this (and more). The downside is browser support - IE10 and above, although most browsers now support it.
To create a horizontal layout with flexbox, you would instruct the parent container to become horizontally oriented. In your case, wrapping the two elements in another element may be beneficial:
<div class="wrapper">
<div id="div1"></div>
<p>Move me</p>
</div>
You then set the wrapper to be a "flex container", where boxes will flow horizontally by default:
.wrapper {
display: flex;
}
There were some experimental flexbox implementations with different syntaxes in the past, so keep that in mind (see example below).
Next, consider sizing the boxes as needed - this is an important aspect of learning about flexbox. :-)
Remember they will still respond to the width
property and adjust accordingly.
If wider browser support is required, combining flexbox with other methods, such as floats or inline block, can work. The beauty of flexbox is that it does not interfere with the display
mode or float
properties of its children, allowing for a mix of old and new techniques.
- Floats are typically used to position images or figures within text blocks, but can also be utilized for complete layouts with some effort. Understanding their behavior may take time. To contain floats within their wrapper, adding
overflow: hidden
is usually effective.
- Inline blocks allow block level elements within text flow, making it possible to create horizontal layouts. Keep in mind that whitespace in the HTML source will translate to empty space between items.
If opting for floats, the code could resemble the following:
.wrapper {
/* various flexbox syntaxes, old */
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
/* modern flexbox syntax */
display: flex;
overflow: hidden; /* contain floats */
}
.wrapper p,
#div1 {
float: left; /* may not be supported by newer browsers */
}