Home  >  Article  >  Web Front-end  >  How to display two divs side by side

How to display two divs side by side

DDD
DDDOriginal
2023-11-01 11:36:591295browse

Methods are: 1. Set the two div elements to the "float:left;" attribute; 2. Use CSS's flex layout to easily display elements side by side; 3. You can also use CSS's grid layout Implement side-by-side display of elements.

How to display two divs side by side

To display two divs side by side, you can use the following methods:

Use the float attribute in CSS, you can use the float attribute to display two divs side by side. The div elements are set to float:left; so that they appear side by side. The sample code is as follows:

<style>
    .div1, .div2 {
        float: left;
        width: 50%; /* 两个div据父素宽度的一半 */
 }
</>
<div class="div1">Div 1</div>
<div class="div2">Div 2</div>

Use flex layout: Using CSS's flex layout can easily display elements side by side. Set the display attribute of the parent element to flex, and set the flex attribute of the child elements to 1, so that they occupy the width of the parent element evenly. The sample code is as follows:

<style>
    .container {
        display: flex;
    }
    .div1, .div2 {
        flex: 1;
    }
</style>
<div class="container">
    <div class="div1">Div 1</div>
    <div class="div2">Div 2</div>
</div>

Use grid layout: Using CSS grid layout can also display elements side by side. Set the display attribute of the parent element to grid, and set the grid-column attribute of the child element to control the position of the child element in the grid. The sample code is as follows:

<style>
    .container {
        display: grid;
        grid-template-columns: 1fr 1fr; /* 将父元素分为两列 */
    }
    .div1 {
        grid-column: 1; /* 第一列 */
    }
    .div2 {
        grid-column: 2; /* 第二列 */
    }
</style>
<div class="container">
    <div class="div1">Div 1</div>
    <div class="div2">Div 2</div>
</div>

The above are three commonly used methods. You can choose the appropriate method according to the specific situation to achieve side-by-side display of two divs.

The above is the detailed content of How to display two divs side by side. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:Reference css in htmlNext article:Reference css in html