简体   繁体   中英

HTML Align DIV Children Horizontally

I am very new in HTML and CSS development. I wanted all children in my div parent align horizontally

My HTML:

<div class="parent">
        <h1>Hello</h1>
        <h1>World</h1>
</div>

I tried using inline-block on .parent like the others suggested but still the output is:

Hello
World

instead

Hello World

any ideas?

The property you're looking for is display: inline; this will make each tag render like it is "inline with each other".

.parent h1 {
    display: inline;
}

You could also float the tags, but I would avoid doing that as it would break the flow of text if you were to add any other tags within the .parent container.

Example JSfiddle

Consider looking at float:left .

 .parent h1 { float:left; } 
 <div class="parent"> <h1>Hello</h1> <h1>World</h1> </div> 

Or even display:inline

 .parent h1{ display:inline; } 
 <div class="parent"> <h1>Hello</h1> <h1>World</h1> </div> 

Keep in mind that using float is not recommended here because if you add a new element to the .parent div it will appear next to the h1 elements because those are floating left. +1 to @MathiasaurusRex for pointing that out.

Another approach is as follows:

 .parent { display: flex; flex-direction: row; }
 <div class="parent"> <h1>Hello</h1> <h1>World</h1> </div>

You dont need to align the div, but need to align the h1's: In your CSS code add:

h1 { display: inline; } h1 { display: inline; } Fiddle here

One thing to note here is your choice of tags h1 for children is wrong, headers inserts an empty line before and after the header. As your motive is only to show some text header tag is not the right tag of choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM