使用浮动元素时自动边距

Posted

技术标签:

【中文标题】使用浮动元素时自动边距【英文标题】:Margin auto when using Float element 【发布时间】:2021-09-04 01:02:07 【问题描述】:

我正在尝试使用 float left 和 center 其中一个容器构建一个响应式网站,我正在尝试使用 margin auto 但它似乎没有做任何事情。

您能指导我如何以响应的方式做到这一点吗?

我知道可能有比使用 float 更智能的解决方案,但我正在尝试了解有关 float 元素的更多信息。

        <style>
    * 
     box-sizing: border-box;
     margin: 0px;
     

     html, body 
     height: 100%;
     

     header 
        height: 30%;
        width: 100%;
        float: left;
        border-style: solid;
     
     nav 
        width: 40%;
        height: 80%;
        border-style: solid;
     

     .navbar 
        float: right;
     

     .part1 
        width: 40%;
        height: 80%;
        border-style: solid;
        margin:  auto;
        float: left;
     

     .whole 

     

     main 
        border-style: solid;
        float: left;
        height: 50%;
        width: 100%;
     

     footer 
        border-style: solid;
        float: left;
        width: 100%;
        height: 20%;
     
    </style>

HTML:

 <body>
        <header>
            <nav class="navbar">
            </nav>
        </header>
        <main class="whole">
            <div class="part1">
            </div>
            <div class="part1">
            </div>
        </main>
        <footer>
        </footer>
    </body>

谢谢

【问题讨论】:

提示:flex 已经使float 的大多数用例过时。 【参考方案1】:

    * 
     box-sizing: border-box;
     margin: 0px;
     

     html, body 
     height: 100%;
     

     header 
        height: 30%;
        width: 100%;
        float: left;
        border-style: solid;
     
     nav 
        width: 40%;
        height: 80%;
        border-style: solid;
     

     .navbar 
        float: right;
     

     .part1 
        width: 40%;
        height: 80%;
        border-style: solid;
        margin:  auto;
        float: left;
     

     .whole 
      display:flex;
     

     main 
        border-style: solid;
        float: left;
        height: 50%;
        width: 100%;
     

     footer 
        border-style: solid;
        float: left;
        width: 100%;
        height: 20%;
     
 <body>
        <header>
            <nav class="navbar">
            </nav>
        </header>
        <main class="whole">
            <div class="part1">
            </div>
            <div class="part1">
            </div>
        </main>
        <footer>
        </footer>
    </body>

【讨论】:

以上是关于使用浮动元素时自动边距的主要内容,如果未能解决你的问题,请参考以下文章

内外边距浮动布局相关

为啥一个元素的 CSS 负边距从浮动框中取出另一个元素

如何使浮动元素的边距折叠

css框模型定位浮动

浮动后IE6双倍边距问题

margin 负边距 的知识点