HTML tutorial: How to use Flexbox for horizontal and equal distribution
In modern web development, flexible and adaptive layout is an important part. Flexbox (flexible layout) is a layout model introduced in CSS3 that provides a simple and powerful way to create flexible container and sub-item layouts. In this tutorial, we will learn how to use Flexbox to achieve horizontal equal distribution.
First, we need to create a basic HTML structure. In the body tag, we create a container with several sub-items. Each child item will collectively occupy the width of the container and will be distributed horizontally.
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Flexbox水平等分布局</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <div class="item">子项目 1</div> <div class="item">子项目 2</div> <div class="item">子项目 3</div> <div class="item">子项目 4</div> </div> </body> </html>
Next, we need to add a style sheet (styles.css) to the HTML file and set the Flexbox layout in it.
.container { display: flex; /* 将容器设置为Flex布局 */ justify-content: space-between; /* 控制子项目的水平分布方式 */ width: 100%; /* 设置容器宽度为100% */ } .item { width: 25%; /* 将每个子项目的宽度设置为25% */ background-color: #ccc; padding: 20px; }
In the above code, we set the container to Flex layout through display: flex
. Then, use justify-content: space-between
to specify how the sub-items should be distributed horizontally, which will preserve equal spacing between each sub-item. Finally, we set the width of each sub-item to 25% to achieve equal distribution horizontally.
Open the HTML file in the browser, you will see that the sub-projects have been distributed horizontally in the container. There is equal spacing between each sub-item and the width is also equal.
Using Flexbox, you can easily extend the layout. For example, if you want to add more sub-items, simply add more <div class="item">...</div>
in the container.
<div class="container"> <div class="item">子项目 1</div> <div class="item">子项目 2</div> <div class="item">子项目 3</div> <div class="item">子项目 4</div> <div class="item">子项目 5</div> <div class="item">子项目 6</div> </div>
In this way, new sub-projects will automatically be distributed horizontally and equally in the container.
By using Flexbox, we can easily achieve a horizontally distributed layout. Flexbox is a simple and powerful layout method that can adapt to various screen sizes and device types, providing us with more flexible layout options. I hope this tutorial is helpful to you, give it a try!
The above is the detailed content of HTML tutorial: How to use Flexbox for horizontal distribution. For more information, please follow other related articles on the PHP Chinese website!