官术网_书友最值得收藏!

  • Mastering CSS
  • Rich Finelli
  • 363字
  • 2021-07-08 09:45:56

Using the clear property to solve basic problems with floats

We can use the clear property to stop elements underneath the floated element from misbehaving. For instance, let's add the clear property to the paragraph. We'll add clear: both, which clears both left and right floated elements:

.content-block p { 
  font-family: Georgia, 'Times New Roman' sans-serif; 
  background-color: green; 
  clear: both; 
} 

Now, when you refresh, you will see the paragraph text seated below the floated element:

We can do the same thing for h1 and that will sit below:

.content-block .figure { 
margin: 30px;
float: right;
}
.content-block h1 { color: #fff; background-color: deeppink; clear: right; }

We can also just say clear: right because the float in the rule set above it is floated to the right.

After saving the CSS and viewing the site, and you will see it works. The h1 tag also sits below .figure:

However, if you type in clear: left to your h1 rule set, it won't necessarily work because there are no left floated elements here:

.content-block h1 { 
  color: #fff; 
  background-color: deeppink; 
  clear: left; 
} 

Following is the output of preceding code block:

Here, None is the default value of both float and clear. So, we can say clear: none on both of these, and it will go back to how it was before we added the clear property:

.content-block h1 { 
  color: #fff; 
  background-color: deeppink; 
  clear: none; 
} 
.content-block p { 
  font-family: Georgia, 'Times New Roman' sans-serif; 
  background-color: green; 
  clear: none; 
} 

Following is the output of preceding code block:

However, since clear: none is the default value, you can just take that whole property away from both of those selectors; this will have the same effect on the site. I hardly ever use clear left and clear right; the both value seems to be more than adequate most of the time.

In this section, we've seen the traditional use of floating elements and how elements underneath the float flow around the floated element. This can be stopped using the clear property. This technique is useful, but honestly, floats are even more useful for building multicolumn layouts. Let's take a look at that now.

主站蜘蛛池模板: 贞丰县| 融水| 如东县| 阿荣旗| 红河县| 高碑店市| 锦屏县| 河曲县| 云阳县| 读书| 定南县| 伊吾县| 梨树县| 高淳县| 大连市| 罗山县| 陆良县| 平昌县| 合江县| 封开县| 虞城县| 乐陵市| 忻州市| 阜康市| 樟树市| 专栏| 安宁市| 太湖县| 朝阳市| 诏安县| 潜江市| 普兰店市| 皮山县| 龙州县| 梅河口市| 广平县| 永德县| 桃园县| 桑植县| 抚宁县| 泗水县|