您现在的位置:首页 >> 前端 >> 内容

关于内层标签margin-top无效的问题

时间:2017/7/4 17:06:23 点击:

  核心提示:关于内层标签margin-top无效的问题最近在页面布局的时候遇到了这么一个问题:!DOCTYPE htmlhtmlheadmeta charset=utf-8title/titlestyle typ...

关于内层标签margin-top无效的问题

最近在页面布局的时候遇到了这么一个问题:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
  <title></title>
  <style type="text/css">
    header{
      width: 940px;
      height: 80px;
      background-color: #000;
      margin: 30px auto;
    }
    header #logo_lg{
      width: 150px;
      height: 30px;
      background-color: green;
      text-align: center;
      margin-left: 27px;
      margin-top: 27px;
    }
  </style>
</head>
<body>
  <header>
    <p class="logo">
      <p href="#" id="logo_lg">我是内层</p>
    </p>
  </header>
</body>
</html>

我是内层如下图,设置了margin-top,但是确没有生效,很是困扰。

关于内层标签margin-top无效的问题

一般块元素不受控制,我都默认是浮动的影响,但在这里我没有浮动。

为了解决这个问题,我将其改为定位。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
  <title></title>
  <style type="text/css">
    header{
      width: 940px;
      height: 80px;
      background-color: #000;
      margin: 30px auto;
      position: relative;
    }
    header #logo_lg{
      width: 150px;
      height: 30px;
      background-color: green;
      text-align: center;
      position: absolute;
      top: 27px;
      left: 27px;
    }
  </style>
</head>
<body>
  <header>
    <p class="logo">
      <p href="#" id="logo_lg">我是内层</p>
    </p>
  </header>
</body>
</html>

我是内层问题就迎刃而解了

关于内层标签margin-top无效的问题

但是这个方式虽然达到了我的目的,但我依然无法理解为何margin-top不起作用。希望将来能找出这个问题的原因,回来将其写上。

相应地办法还可以给其父元素设置padding:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
  <title></title>
  <style type="text/css">
    header{
      width: 913px;
      height: 53px;
      background-color: #000;
      margin: 30px auto;
      padding-top: 27px;
      padding-left: 27px;
    }
    header #logo_lg{
      width: 150px;
      height: 30px;
      background-color: green;
      text-align: center;
    }
  </style>
</head>
<body>
  <header>
    <p class="logo">
      <p href="#" id="logo_lg">我是内层</p>
    </p>
  </header>
</body>
</html>

我是内层但是也要给父元素的宽高都相应地减少同样的像素,结果如下:

关于内层标签margin-top无效的问题

作者:网络 来源:HIDPROVIDE