Code前端首页关于Code前端联系我们

CSS属性

terry 2年前 (2023-09-07) 阅读数 214 #CSS
文章标签 CSS百科float

float一直是CSS中非常重要的话题。

这是一种创造性的使用方式,因为它是为数不多的几种方式之一,就像桌子一样,我们可以得到一些布局。例如,过去我们经常将侧边栏向左浮动,使其出现在屏幕的左侧,并为主要内容添加一些边距。

幸运的是,时代变了,现在我们有了 Flexbox 和 Grid 来帮助布局,而 float 又回到了他原来的范围:将内容放在容器元素的一侧,并允许其兄弟元素显示在其周围。

float 属性支持 3 个值:

.parent {
  background-color: #af47ff;
  padding: 30px;
  width: 500px;
}

.child {
  background-color: #ff4797;
  padding: 30px;
}

.box {
  background-color: #f3ff47;
  padding: 30px;
  border: 2px solid #333;
  border-style: dotted;
  font-family: courier;
  text-align: justify;
  font-size: 1rem;
}
  • 无(默认)
  • 假设我们有一个包含几段文本的盒子,其中还包含图像。

    以下是一些代码:

    <div class="parent">
      <div class="child">
        <div class="box">
          <p>This is some random paragraph and an image. <img src="https://via.placeholder.com/100x100" /> The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text.
          </p>
        </div>
      </div>
    </div>
    .parent {
      background-color: #af47ff;
      padding: 30px;
      width: 500px;
    }
    
    .child {
      background-color: #ff4797;
      padding: 30px;
    }
    
    .box {
      background-color: #f3ff47;
      padding: 30px;
      border: 2px solid #333;
      border-style: dotted;
      font-family: courier;
      text-align: justify;
      font-size: 1rem;
    }

    显示以下效果:

    CSS float属性

    正如您所看到的,默认情况下,正常流程会考虑内联图像并为排队的人腾出空间。

    如果我们在图像中添加 float: left 和一些填充:

    img {
      float: left;
      padding: 20px 20px 0px 0px;
    }

    结果如下:

    CSS float属性

    以下是通过float调整padding:对了,结果如下:

    img {
      float: right;
      padding: 20px 0px 20px 20px;
    }
    CSS float属性

    浮动元素从页面的正常流程中移除,其余内容围绕其流动。

    你不限于浮动图像,这里我们使用span元素来改变图像:

    <div class="parent">
      <div class="child">
        <div class="box">
          <p>This is some random paragraph and an image. <span>Some text to float</span> The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text.
          </p>
        </div>
      </div>
    </div>
    span {
      float: right;
      margin: 20px 0px 20px 20px;
      padding: 10px;
      border: 1px solid black
    }

    结果如下:

    CSS float属性

    版权声明

    本文仅代表作者观点,不代表Code前端网立场。
    本文系作者Code前端网发表,如需转载,请注明页面地址。

    上一篇:CSS 浮动 下一篇:Normalize.css介绍及使用

    发表评论:

    ◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

    热门