Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/CSS float: left; is not working properly

Tags:

html

css

I'm currently reading Headfirst CSS/HTML and I'm having an issue with an example.

I'm attempting to float the body to the left of the sidebar using float:left; however it's not floating properly. I've been over the HTML and CSS an I can't quite see what's wrong.

This is what I want it to look like:

enter image description here

And the fiddle: https://jsfiddle.net/Taubin/7Lhz4wtd/

#main {
  background: #efe5d0 url(images/background.gif) top left;
  font-size:  105%;
  padding:    15px;
  margin:     0px 10px 10px 10px;
  width:      420px;
  float:      left;
}
<div id="allcontent">
  <div id="header">
  </div>
  <div id="sidebar">
    <p class="beanheading">
      Sidebar text
    </p>
    <p>
      Sidebar text
    </p>
  </div>
  <div id="main">
    <h1>QUALITY COFFEE, QUALITY CAFFEINE</h1>
    <p>
      Main text
    </p>
  </div>
</div>

Any suggestions would be greatly appreciated.

like image 356
Taubin Avatar asked Feb 20 '26 07:02

Taubin


2 Answers

First, it might be the issue that you are adding margin and paddings, which add size to the box even though the box has a width of 420px, you have to calculate margins and paddings to, or use * { box-sizing: border-box; }, which will calculate the width of that element as a sum of all the sizes (padding, margin, width) and not exceed the width.

Second, the order of the elements are important when floating, put main always on top of the sidebar, since elements start as top to bottom, when you float a top element, the bottom element if its wider, will collapse and align with the main box.

Screenshot for reference:

enter image description here

like image 134
sadiqevani Avatar answered Feb 22 '26 22:02

sadiqevani


Here is the https://jsfiddle.net/bg2v0dqn/.

You shouldn't add a large gap with margin.

Here's what I changed:

#main {
  background:       #efe5d0 url(images/background.gif) top left;
  font-size:        105%;
  padding:          15px;
  margin:           0px 10px 10px 10px;
  width:            420px;
  float:            left;
}

#sidebar {
  background:       #efe5d0 url(images/background.gif) bottom right;
  font-size:        105%;
  padding:          15px;
  margin:           0px 10px 10px 0;
    width: 290px;
    float: right;
}
like image 40
Jessica Avatar answered Feb 22 '26 21:02

Jessica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!