【问题标题】:margin-button is not moving element边距按钮不移动元素
【发布时间】:2020-02-16 20:40:02
【问题描述】:

我正在尝试使用 div 和前后选择器创建 3 行。在 after 中应用 margin-top 会向下移动线条,但在 margin-bottom 之前应用不会向上移动线条。

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Playground</title>
    <style>
        body {
            height: 100vh;
        }

        #area {
            width: 500px;
            height: 5px;
            background: #333;
        }

        #area::after {
            content: "";
            width: 500px;
            height: 5px;
            margin-top: 15px;
            background: red;
            display: block;
        }

        #area::before {
            content: "";
            width: 500px;
            height: 5px;
            margin-bottom: 15px;
            background: blue;
            display: block;
        }
    </style>
</head>

<body>
    <div id="area">

    </div>
</body>
</html>

【问题讨论】:

  • 使用margin-bottom 代表#area::aftermargin-top 代表#area::before
  • margin-bottom 不会向上移动,它会在向下推动元素。一个页面布局如果从上到下所以我们总是移动底部。负边距可能会拉起元素

标签: html css


【解决方案1】:

::before 和 ::after 元素在正常流程中仍然出现在它们的元素内部,因此您必须使用一些相对和绝对定位来实现此效果:

#area {
  width: 500px;
  height: 5px;
  background: #333;
  position: absolute;
  margin-top: 30px;
}

#area::before {
  content: "";
  width: 500px;
  height: 5px;
  position: absolute;
  top: -10px;
  background: blue;
  display: block;
}

#area::after {
  content: "";
  width: 500px;
  height: 5px;
  position: absolute;
  top: 10px;
  background: red;
  display: block;
}
&lt;div id="area"&gt;&lt;/div&gt;

【讨论】:

  • 感谢您的回答,这是有效的,但为什么在这种情况下边距不起作用。
猜你喜欢
  • 2010-12-18
  • 2023-03-17
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
相关资源
最近更新 更多