Aharon Snyder
Aharon Snyder

Reputation: 45

Adding text to div breaks the initial alignment

On to the real question. I started learning HTML and I ran into a circumstance that I don't understand why it happens and was hoping someone could explain this to me. My HTML Code My CSS code

Above is my code and what I don't get is why the introduction of the word text in box1 causes the whole box to be displayed on a new line. enter image description here Once the text is removed it realigns. any help is welcome.

I'm going to end this off by saying that I tried pasting in code (using the code blocks button and surrounding my code with <code> and <pre> tags but the editor would not display the code or would break the code block by every second)

Upvotes: 1

Views: 931

Answers (2)

Adnan Akram
Adnan Akram

Reputation: 641

Try vertical-align:top; with inline-block.

When we use inline-block we can align blocks in 3 different way's, like if 2 block have large height and one has small then using vertical-align:top; make all three block aligned at top using vertical-align:middle; make these three block aligned middle and using vertical-align: bottom; make these blocks aligned at the bottom side

div {
  display: inline-block;
  vertical-align:top;
  margin: 25px;
  }

p {
   padding: 10px;
  text-align: center;
  }

#box1 {
  width: 100px;
  height: 100px;
  background-color: red;
  }
#box2 {
   width: 100px;
  height: 100px;
  background-color: blue;
  }
#box3 {
    width: 100px;
  height: 100px;
  background-color: yellow;
  }
<div id="container">
    <div id="box1"><p>text</p></div>
    <div id="box2"></div>
    <div id="box3"></div>
</div>

Upvotes: 4

HTMLNoob
HTMLNoob

Reputation: 821

It is because you have a pixel value for the width and height of all 3 of your divs. The text "increases" the width and pixel value of your divs.

UPDATE

Why not use the float property?

div {
  float: left;
  display: block;
   margin: 25px;
  }

p {
   padding: 10px;
  text-align: center;
  }

#box1 {
  width: 100px;
  height: 100px;
  
  background-color: red;
  }
#box2 {
   width: 100px;
  height: 100px;
  background-color: blue;
  }
#box3 {
    width: 100px;
  height: 100px;
  background-color: yellow;
  }
<div id="container">
    <div id="box1"><p>text</p></div>
    <div id="box2"></div>
    <div id="box3"></div>
</div>

Upvotes: 2

Related Questions