CSS makes the upper div the same width as the lower div
CSS makes the top div the same width as the bottom div
In this article, we’ll show you how to use CSS to make the top div the same width as the bottom div The effect is the same width as the div below it.
Read more: CSS Tutorial
Using the Box Model
To make two div elements the same width, first understand the concept of the box model. In CSS, each element is considered a rectangular box, including content, padding, borders, and margins. The width of an element is determined by the width of its content area plus the width of its left and right padding. By setting the box model properties, we can control the width of an element.
Use flex layout
Flex Layout is a modern, flexible layout method that allows you to set the width of the upper and lower divs to be equal. Applying the display: flex
property to a container treats its children as a flexible box. Then, you can use the flex: 1
property to set the two div elements to equal width.
.container {
display: flex;
}
.container > div {
flex: 1;
}
This way, the upper and lower divs will be displayed with equal widths.
Using Grid Layout
Grid Layout is a two-dimensional layout system that divides a page into rows and columns, allowing elements to be placed within this grid. Using Grid Layout, we can easily set the width of the top and bottom divs to be equal.
.container {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: auto;
}
.container > div {
grid-row: 1;
grid-column: 1;
}
In this example, we set the container’s grid to a single column, and the row and column of the child elements to 1. This way, the top and bottom divs will be rendered with equal widths.
Using JavaScript
If setting the width of the top and bottom divs to equal isn’t possible using pure CSS, we can also use JavaScript.
const topDiv = document.querySelector('.top-div');
const bottomDiv = document.querySelector('.bottom-div');
const width = bottomDiv.offsetWidth;
topDiv.style.width = `${width}px`;
By obtaining the width of the lower div and then applying that width to the upper div, you can achieve the effect of equal width for both divs.
Summary
Through the box model, Flex layout, grid layout, and