簡體   English   中英

在 HTML 和 CSS 中,浮動和寬度沒有做它們應該做的事情

[英]Float and width are not doing what they should be doing in HTML and CSS

我的代碼有兩個問題: (1) CSS 中的 float 參數影響了應該完全不相關的項目, (2) width 或 float 或兩者都沒有按預期與另一個元素一起工作(繼續閱讀,它會更簡單)。

HTML:

<nav>
    <a class="nav-title-link" href="/">
        <div class="nav-logo-section">
            <div id="titleText" class="title-text">
                <h2>My Title</h2>
            </div>
            <img class="nav-logo" src="MY SOURCE">
        </div>
    </a>
    <div id="navRight" class="nav-right">
        <!-- Some content here that is irrelevant to the problem -->
    </div
</nav>
<div id="irrelevant">
    <div class="main-content">
        <h1 class="main-title">Catchphrase</h1>
        <p class="main-paragraph">Some text here</p>
    </div>
    <div id="box" class="box">
       <!-- Some content in the box -->
    </div>
</div>

CSS:

.nav-logo-section {
    margin: 5px 10px 5px 30px;
    float: left;
}
.nav-logo {
    height: 50px;
}
.title-text {
    color: #252f3f;
    line-height: 0.5;
    float: left;
}

.main-content {
    padding: 50px 75px 0 75px;
    width: calc(50% - 150px);
    float: left;
}

.box {
    float: right;
    margin: 75px 100px 0 0;
    width: 400px;
    padding: 20px;
    border-radius: 35px;
    box-shadow: 0px 5px 10px 0 rgba(0, 0, 0, 0.3);
    background: white;
}

第一個問題

出於某種原因, nav-logo-section似乎影響了main-content的 position,如下圖所示( main-content應幾乎與屏幕左側齊平):

這是代碼的結果(第一個問題)

第二個問題

第二個問題是當我刪除float: leftmain-content元素上以避免第一個問題時, box元素沒有 go 與main-content元素並排,如下圖所示:

這是代碼的結果(第二個問題)

我發現的一個可能的問題是,出於某種原因, width似乎充當了main-content元素中的margin ,如檢查網頁時所見:

這就是主要內容 div 的樣子

我真的被困在這里,正如你所看到的,一切都有些混亂。 如果您有任何可能的解決方案,請告訴我。 謝謝

使用 flexbox 作為導航而不是浮動怎么樣? 基本上你在導航中有 2 個部分,一個拉到左邊,一個拉到右邊,你可以使用

.nav{
display: flex,
width: 100%
justify-content: space-between
}

也許 flexbox 也可以幫助您解決第二個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM