Home  >  Article  >  Web Front-end  >  Usage of float in css

Usage of float in css

下次还敢
下次还敢Original
2024-04-28 13:36:18986browse

The float attribute floats the element on the page and displays it side by side with adjacent elements without affecting the regular fluid layout. The float values ​​are: left (left float), right (right float), none (clear float). Floated elements affect content overflow, spacing, and parent container height. Methods for clearing floats include: clearing attributes, floating elements, and overflow: hidden.

Usage of float in css

Usage of float in CSS

float definition

CSS The float property positions the element outside its content box, causing it to float on the page. Floated elements do not affect the regular flow layout of other elements, but appear side by side with their adjacent elements.

float value

The float attribute can accept the following values:

  • #left: Float the element to the container's left side.
  • right: Float the element to the right side of the container.
  • none: Clear the float and return the element to normal fluid layout.

Usage

To float an element, add the float attribute to its style:

element {
  float: left;
}

Influence

Floating elements will affect their nearby elements:

  • Content overflow: The content of a floating element may overflow its adjacent elements.
  • Spacing: There may be spacing between floating elements and adjacent elements.
  • Parent container height: If the height of the floating element is higher than the parent container, the height of the parent container will automatically adjust to accommodate the floating element.

Clear Floats

To clear floats, you can use one of the following methods:

  • Clear attributes:Apply the clear attribute to an element and clear all its floating elements.
  • Floating element: Add a floating element after the floating element and clear the floating element to a new row.
  • overflow: hidden: Apply the overflow attribute to the parent container to hide floating elements in the container.

Example

The following code creates a container with two floating elements:

元素 1
元素 2
.container {
  display: flex;
}

.element1 {
  float: left;
  background: red;
  width: 100px;
}

.element2 {
  float: right;
  background: blue;
  width: 100px;
}

Output:

元素 1 | 元素 2

The above is the detailed content of Usage of float in css. 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