Home > Web Front-end > CSS Tutorial > How to Align Div Elements Side by Side in HTML and CSS?

How to Align Div Elements Side by Side in HTML and CSS?

Mary-Kate Olsen
Release: 2024-12-20 03:59:14
Original
815 people have browsed it

How to Align Div Elements Side by Side in HTML and CSS?

Align
elements side by side

Many ways to do it, beware float: left…

There are many ways to align elements side-by-side. Below are the most common ways to achieve two elements side-by-side…

Demo: View/edit all the below examples on Codepen


Basic styles for all examples below…

Some basic css styles for parent and child elements in these examples:

.parent {<br>  background: mediumpurple;<br>  padding: 1rem;<br>}<br>.child {<br>  border: 1px solid indigo;<br>  padding: 1rem;<br>}<br>


Use float: left with caution

Using the float solution may have unintended effects on other elements. (Hint: You may need to use a clearfix.)

html

<div>  <div class='child float-left-child'>A</div><br>  <div></div><br>

css

  float: left;<br>}<br>


Using display: inline-block is straightforward

html

<div>  <div class='child inline-block-child'>A</div><br>  <div></div><br>

css

  display: inline-block;<br>}<br>


display: inline-block and removing the space between divs

Note: the space between these two child elements can be removed, by removing the space between the div tags:

html

<div>  <div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div><br></div><br>

css

  display: inline-block;<br>}<br>


display: flex is a good choice

html

<div>  <div class='child flex-child'>A</div><br>  <div></div><br>

css

  display: flex;<br>}<br>.flex-child {<br>  flex: 1;<br>}<br>


display: inline-flex is similar to display: flex but inline

html

<div>  <div class='child'>A</div><br>  <div></div><br>

css

  display: inline-flex;<br>}<br>


With display: grid, you can fine tune the layout

html

<div>  <div class='child'>A</div><br>  <div></div><br>

css

  display: grid;<br>  grid-template-columns: 1fr 1fr<br>}<br>


The above is the detailed content of How to Align Div Elements Side by Side in HTML and CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template