The solution to the parent element being affected by the margin-top of the child element in CSS

When the style of the parent element is affected by the margin-top of the child element, the following methods can be used to solve it:

1. Use overflow: hidden on the parent element: set overflow: hidden to hide the part beyond the scope of the parent element

#parent {
  overflow: hidden;
}

2. Use padding on the parent element: add corresponding padding to the parent element

#parent {
  padding-top: 20px; /* 与子元素的 margin-top 相同的值 */
}

 3. Use box-sizing on the parent element: set box-sizing to border-box so that the border and padding of the parent element are also included in the total width and height of the element

#parent {
    box-sizing: border-box;
}

 4. Use the position attribute on the parent element: set the position of the parent element to relative

#parent {
    position: relative;
}

5. Use the ::before pseudo-element on the parent element: Create a ::before pseudo-element on the parent element and set its margin-top to a negative value

#parent::before {
    content: "";
    margin-top: -20px; /* 与子元素的 margin-top 相反的值 */
    display: block;
}

6. Use flexbox layout: Using flexbox layout can make the child element vertically centered in the parent element, so as to avoid the parent element being affected by the margin-top of the child element (this method is generally not considered, unless it is a special requirement)

#parent {
    display: flex;
    align-items: center;
}

7. Use grid layout: Use grid layout to vertically center the child element in the parent element, avoiding the parent element being affected by the margin-top of the child element (this method is generally not considered, unless it is a special requirement)

#parent {
    display: grid;
    place-items: center;
}

These methods can prevent the parent element from being affected by the margin-top of the child element, but you need to choose which method to use according to the project requirements and page layout.

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/131276410