Home  >  Article  >  Web Front-end  >  css float does not wrap

css float does not wrap

王林
王林Original
2023-05-09 09:19:371940browse

In the process of web page creation, we often use the float attribute of CSS to arrange multiple elements in the same row or column. But sometimes floating elements are assigned to the next line. At this time, we need to master some skills to prevent floating elements from wrapping.

1. Clear floats

If the width of a floating element is not set, it will occupy the width of the parent element by default. If the height of the parent element is not enough, the floating element will be "squeezed" to the next line. So how to solve this problem? You can use the clear float technique. Common methods of clearing floats are as follows:

1. Use clearfix

to add the "clearfix" class in the CSS style of the parent element, as shown below:

.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

In HTML , add the class name "clearfix" to the parent element, as shown below:

Left
Left

2. Use pseudo-classes to clear floats

Add pseudo-class ":before" in the CSS style of the parent element Or ":after", as shown below:

.parent:after {
    content: "";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

In HTML, add the class name "parent" to the parent element, as shown below:

Left
Left

2. Use display: inline-block

In addition to clearing floats to prevent floating elements from wrapping, you can also use the "display: inline-block" attribute. This attribute allows the element to have the characteristics of an inline block-level element. The height can be set while maintaining the same line display.

Inline-block
Inline-block

3. Use setting width

If the floating element has a width set, it will be displayed on the same line even if the parent element is not tall enough.

Left Float
Right Float

4. Use elastic layout

Elastic layout is a layout method provided by CSS3, which is very convenient when multiple elements are arranged in the same row or column. To use flexible layout, you only need to set the "display: flex" attribute on the parent element to allow the child elements to perform adaptive layout.

Flex 1
Flex 2

The above are several ways to prevent floating elements from wrapping. You can choose the method that suits you according to the actual situation.

The above is the detailed content of css float does not wrap. 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:css set text contentNext article:css set text content