Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these divs not horizontally aligned? Why do they line break?

This HTML:

<div style="border:1px solid blue; margin: auto; height:250px; width:600px;">
    <div style="border:1px solid red; height:50px; width:80px;"></div>
    <div style="border:1px solid red; height:50px; width:80px;"></div>
    <div style="border:1px solid red; height:50px; width:80px;"></div> 
    <div style="border:1px solid red; height:50px; width:80px;"></div>
</div>

Why are the red divs not in the same horizontal row and how do I get them in the same row?

like image 725
Morten Pedersen Avatar asked Sep 21 '14 01:09

Morten Pedersen


People also ask

How to align a Div horizontally using CSS?

To align div horizontally, one solution is to use css float property. But a better solution is to to use CSS display:inline-block on all divs which needs to be aligned horizontally and place them in some container div. Here is are some examples. Default vertical-align value is baseline.

How to prevent a Div from breaking to the next line?

An HTML <div> (division) is a block-level elementdesigned to not display any HTML elements next to it unless its default behavior is changed. Below are all the different methods of preventing a div from breaking to the next line. Tip Depending on why you want to break a div, also consider a <span> tag.

What is a division in HTML?

An HTML <div> (division) is a block-level elementdesigned to not display any HTML elements next to it unless its default behavior is changed. Below are all the different methods of preventing a div from breaking to the next line.

What is the default Div behavior of the block element?

Below is an example of the default div behavior of the block element Div oneoccupying the first line of its containing element followed by the second Div two. Div one Div two HTML code


1 Answers

Here's what you looking for:

<style type="text/css">
    div.littleDiv {
        display: inline-block;
        border:1px
        solid red; 
        height:50px; 
        width:80px;
    }
</style>
<div style="border:1px solid blue; margin: auto; height:250px; width:600px;">
    <div class="littleDiv"></div>
    <div class="littleDiv"></div>
    <div class="littleDiv"></div> 
    <div class="littleDiv"></div>
</div>

This has been possible for a long time using float, but now with inline-block it's even easier. inline-block elements are like inline elements but they can have a width and height.

However you might want to use float: lefts instead of display: inline-block;

From MDN

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.

like image 67
Adam Sinclair Avatar answered Sep 23 '22 14:09

Adam Sinclair