zoukankan      html  css  js  c++  java
  • 子级div设置margin属性影响父级位置

    前端开发中,有时候会遇到设置子级div的margin属性后,导致整个父级div整体移动,有时候却是正常的,时而正常时而有异常。

    一、问题描述:

    1、css未设置margin属性时,效果图如下:

    没有margin设置

    2、css设置 margin-top:50px 属性时,预期效果图如下:

    预期效果图

    3、css设置 margin-top:50px 属性时,实际效果图如下:

    子级margin设置

    二、解决方案:

    1、  给父级增加padding属性

    .父级class{
        padding: 10px;// 任意值都可以
    }

    2、给父级增加border属性

    .父级class{
        border: 1px solid transparent;// 是否有颜色自行处理
    }

    三、产生问题原因:

    一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其内部文档流中的第一个子元素的上边距重叠。、

    复现代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
          html,body{
            width:100%;
            height:100%;
          }
          .content{
            width:40%;
            height:40%;
            position: relative;
            border: 1px solid transparent; //为了解决文中所说问题
          }
          span {
            position: absolute;
            padding: 2px;
            border-style: solid;
            border-color: #04384e;
          }
          .row1 {
            border-width: 2px 0 0 2px;
            top: -2px;
            left: -2px;
          }
          .row2 {
            border-width: 2px 2px 0 0;
            top: -2px;
            right: -2px;
          }
          .col1 {
            border-width: 0 0 2px 2px;
            bottom: -2px;
            left: -2px;
          }
          .col2 {
            border-width: 0 2px 2px 0;
            bottom: -2px;
            right: -2px;
          }
          .title {
            font-size: 16px;
            color: #3cbeda;
            height: 28px;
            line-height: 28px;
            margin: 15px;
            padding-left: 10px;
            border-left: 5px solid #05c8e8;
            text-indent: 10px;
            background: rgba(5, 76, 107, 0.5);
            background-clip: content-box;
          }
    
    
        </style>
    </head>
    <body>
      <div class="content">
        <span class="row1"></span>
        <span class="row2"></span>
        <span class="col2"></span>
        <span class="col1"></span>
        <div class="title">
          二级单位接入进度排名
        </div>
      </div>
    </body>
    </html>

    效果图如下:

  • 相关阅读:
    c内存结构
    Linux普通文件和设备的异同点
    二分查找在字符串中的应用范例
    快排的一种相当简单但不算最快的实现方式
    C程序的存储空间布局
    exit与_exit
    /proc文件系统
    Linux下监控磁盘空间的四个命令
    linux下监控进程需掌握的四个命令
    linux终端下文件不同颜色的含义
  • 原文地址:https://www.cnblogs.com/yuwenjing0727/p/13646892.html
Copyright © 2011-2022 走看看