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.
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!