在第 2 组段落上浮动不适用 - CSS - 浮动

问题描述 投票:0回答:1

我正在上 coursera 课程(约翰霍普金斯大学)并且已经完成了关于浮动的 CSS 讲座。

我不想只在第 1 2 3 4 段的第一组上更改 CSS 应用程序,我想将浮动示例的修改应用到另一组第 5 6 7 8 段上。

这是 HTML:

<H1>Floating Part One</H1>
        <div>
            <p id="P1"></p>
            <p id="P2"></p>
            <p id="P3"></p>
            <p id="P4"></p>
        </div>  

     <H1>Floating Part 2</H1>
        <div id="div2">
        <p id="P5"></p>
        <p id="P6"></p>
        <p id="P7"></p>
        <p id="P8"></p>
       
    </div>
    <section>We've removed the float right part and just make every paragraph float to the left with a margin right 10px </section>

这是CSS

div {
    background-color: #00FFFF;}

#div2 {background-color: #00FFFF;}

p {width: 50px;
    height: 50px;
    border: 1px solid black;
}

#P1 {background-color: #A52A2A;
float: right}

#P2 {background-color: #DEB887;}

#P3 {background-color: #5F9EA0;}

#P4 {background-color: #FF7F50;}


section
{
    background-color: rgb(52, 143, 36);
    color: black;
    font-size: 120%;
    text-align: left;
    height: 50px;
    margin: 10px;
    border: solid black;
    padding: 20px;
}

p #div2 {width: 50px;
    height: 50px;
    border: 1px solid black;
    float: left;
    margin-right: 10px; 
}

#P5 {background-color: #A52A2A;}
    
#P6 {background-color: #DEB887;}
    
#P7 {background-color: #5F9EA0;}
    
#P8 {background-color: #FF7F50;}

我试图让嵌套在“Div2”中的所有段落都应用到所有浮动的左边, 这应该减小 Div2 的大小,并将所有第 5、6、7、8 段按照类别排列。但我没有达到它。

html css css-float
1个回答
0
投票

最简单的方法是使用

flex
。在使用 css 定位事物时,请始终避免使用
float
并使用
flex
grid
代替。您可以通过将每一列包装在一个 div 中并将两列包装在另一个 div 中来实现这一点。使用 flex,您可以轻松定义元素之间的对齐方式和空间,以及它们在构建响应式布局时的行为方式:

我是这样修复的:

<html lang="en">
  <head>
    <title>Home</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <!--
      Need a visual blank slate?
      Remove all code in `styles.css`!
    -->
    <link rel="stylesheet" href="styles.css" />
    <script type="module" src="script.js"></script>
  </head>
  <body>
    <div class="wrapper">
      <div>
        <h1>Floating Part One</h1>
        <div>
          <p id="P1">Some text</p>
          <p id="P2">Some text</p>
          <p id="P3">Some text</p>
          <p id="P4">Some text</p>
        </div>
      </div>

      <div>
        <h1>Floating Part 2</h1>
        <div id="div2">
          <p id="P5">Some more text</p>
          <p id="P6">Some more text</p>
          <p id="P7">Some more text</p>
          <p id="P8">Some more text</p>
        </div>
      </div>
    </div>
    <section class="footer">
      We've removed the float right part and just make every paragraph float to
      the left with a margin right 10px
    </section>
  </body>
</html>

在 css 上我刚刚添加了以下类:

.wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

这里有一个正常运行的 Stackblitz https://stackblitz.com/edit/web-platform-dt16qz?file=index.html

© www.soinside.com 2019 - 2024. All rights reserved.