Some weird thing with clear both via css pseudo :after

点点圈 提交于 2019-12-20 07:49:08

问题


Examine this code:

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

Why is the clear both with the after element not working in this example above? while the clearing with <div style="clear:both"></div> inside the layout it self do work.


回答1:


The :after clear float trick works on floated element inside the pseudo elements parent.

If you would put the <div style="clear:both"></div> inside the h1 it will not clear the float either, so it has to be a sibling or a parent element of the floated element

So in your case just clear the float on the 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">



回答2:


Try this, add display: block to input:

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




回答3:


It would be good if you provide clearfix to parent element try this snippet hope this could help you. I'm also including :before but this is the best way to clear the floats. here is the jsfiddle link 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">


来源:https://stackoverflow.com/questions/35321992/some-weird-thing-with-clear-both-via-css-pseudo-after

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!