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

There are two problems with my code: (1) the float parameter in CSS is affecting items that should be completely irrelevant and (2) either width or float or maybe both are not working as expected with another element (carry on reading and it will be simpler).

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;
}

1st Problem

For some reason, the nav-logo-section seems to be affecting the position of the main-content as seen in the image below (the main-content should be almost flush with the left side of the screen):

This is the result of the code (1st problem)

2nd Problem

The second problem is when I remove float: left on the main-content element to avoid the 1st problem the box element doesn’t go side by side with the main-content element as seen in the image below:

This is the result of the code (2nd problem)

A possible problem that I found is that width seems to be acting as a margin in the main-content element for some reason as seen when inspecting the webpage:

This is what the main-content div looks like

I am really stuck here and as you can see, everything is a bit of a mess. If you have any possible solutions please tell me. Thank you

>Solution :

What about using flexbox for the nav insteado of float? Basically you have 2 sections inside the nav, one pulled to the left and one pulled to the right, you can use

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

And perhaps flexbox can help you to the second problem as well

Leave a Reply