【问题标题】:Some weird thing with clear both via css pseudo :after通过css伪清除一些奇怪的东西:after
【发布时间】:2016-02-10 17:29:59
【问题描述】:

检查这段代码:

HTML

<h1 class="one">Sometext over here</h1>
<input type="text" placeholder="E-mail" class="two">

CSS

.one {
display: block;
float: left;
width: 450px;
height: 60px;
padding-top: 25px;
color: #ffffff;
font-size:34px;
font-weight: 800;
}
.one:after { clear: both; }
.two {
margin: 0 auto;
font-size: 150%;
width: 200px;
height: 20px;
  }

JSfiddle

为什么带有after 元素的clear both 在上面的示例中不起作用?而在布局内使用&lt;div style="clear:both"&gt;&lt;/div&gt; 清除它自己可以工作。

【问题讨论】:

  • 你想做什么?
  • 试试这个 .one:after { content: "";显示:表格;明确:两者; }
  • 试过了......伪元素没有任何作用。我无法得到它...
  • 大声笑。人们投了反对票,但没有提供任何解决方案......太棒了:)

标签: html css css-float pseudo-element


【解决方案1】:

试试这个,在输入中添加display: block

CSS

.one {
  display: block;
  width: 450px;
  height: 60px;
  padding-top: 25px;
  color: #ffffff;
  font-size: 34px;
  font-weight: 800;
  text-align: left;
}

.two {
  font-size: 150%;
  width: 200px;
  height: 20px;
  display: block;
  margin:0 auto;
}

HTML

<h1 class="one">Sometext over here</h1>
<input type="text" placeholder="E-mail" class="two">

DEMO HERE

【讨论】:

  • 有点奇怪...我用我所有的浏览器都试过了...IE、ff、chrome、opera...它不是以我为中心的。什么鬼……
  • 还有我给你的网址……你看看是否可以? - jsfiddle.net/luispa/2dhv5t61/2
  • 之前尝试过显示块。这是我得到的:i.stack.imgur.com/QwvFp.png
  • 我在不使用浮点数的情况下更新我的答案 - jsfiddle.net/luispa/2dhv5t61/5
  • 我知道,Luis :) 我可以让它在没有浮动的情况下工作,我只是无法理解这种在使用普通 div 时不使用伪元素清除浮动的行为
【解决方案2】:

:after 清除浮动技巧适用于浮动元素伪元素父元素内。

如果您将&lt;div style="clear:both"&gt;&lt;/div&gt; 放在h1 中,它也不会清除浮动,因此它必须是浮动元素的兄弟元素或父元素

所以在你的情况下,只需清除 input 上的浮动

.one {
  float: left;
  width: 450px;
  height: 60px;
  padding-top: 25px;
  color: #ccc;
  font-size:34px;
  font-weight: 800;
}
.two {
  display: block;
  margin: 0 auto;
  font-size: 150%;
  width: 200px;
  height: 20px;
  clear: both;
}
<h1 class="one">Sometext over here</h1>
<input type="text" placeholder="E-mail" class="two">

【讨论】:

    【解决方案3】:

    如果你向父元素提供clearfix 会很好,试试这个 sn-p 希望这可以帮助你。我还包括:before,但这是清除浮动的最佳方法。这是jsfiddle链接https://jsfiddle.net/rhulkashyap/jjv6t6gd/

    .one {
      display: block;
      float: left;
      width: 450px;
      height: 60px;
      padding-top: 25px;
      color: #111;
      font-size: 34px;
      font-weight: 800;
    }
    .clearfix:before,
    .clearfix:after {
      content: "";
      display: table;
    }
    .clearfix:after {
      clear: both;
    }
    .clearfix {
      *zoom: 1;
    }
    .two {
      margin: 0 auto;
      font-size: 150%;
      width: 200px;
      height: 20px;
    }
    <div class="clearfix">
      <h1 class="one">Sometext over here</h1>
    </div>
    <input type="text" placeholder="E-mail" class="two">

    【讨论】:

    • 我可以简单地在h1 标签之后使用&lt;div style="clear:both"&gt;&lt;/div&gt;...我不是在寻找额外的布局
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    相关资源
    最近更新 更多