Azat
Azat

Reputation: 1148

Why does block with text shift to bottom?

Why does block with text shift to the bottom? I know how to fix this issue (need to add "overflow: hidden" to the box), but I don't understand why it shift to the bottom, text inside the box is short, margins in browser-inspector are same as margins of example without text.

Example of the problem

HTML:

<div class="with-text">
  <div class="box1">
    SIMPLE TEXT
  </div>
  <div class="box2">
  </div>
</div>
<div class="without-text">
  <div class="box1">
  </div>
  <div class="box2">
  </div>
</div>

CSS:

html, body {
  font-size: 10px;
  margin: 0;
  height: 100%;
}

.box1 {
  display: inline-block;
  margin: 5px;
  width: 50px;
  height: 50px;
  background: blue;
  /* Fix the problem */
  /* overflow: hidden; */
  color: white;
}

.box2 {
  display: inline-block;
  margin: 5px;
  width: 50px;
  height: 50px;
  background: red;
}

.with-text:before {
  display: block;
  content: "with-text";
  text-transform: uppercase;
  margin: 1rem;
}

.with-text {
  box-sizing: border-box;
  height: 50%;
  border: 1px solid;
}

.without-text:before {
  display: block;
  content: "without text";
  text-transform: uppercase;
  margin: 1rem;
}

.without-text { 
  box-sizing: border-box;
  height: 50%;
  border: 2px solid black;
}

Upvotes: 4

Views: 202

Answers (2)

Bhupat Bheda
Bhupat Bheda

Reputation: 1978

The problem is that by default vertical alignment of inline elementsbaseline,

The text inside element affects it and pushes div to the bottom.

Use vertical-align: top to solve issue.

Upvotes: 2

Catherine Levchenia
Catherine Levchenia

Reputation: 1

You can try to add vertical-align:

.box1 {
  display: inline-block;
  margin: 5px;
  width: 50px;
  height: 50px;
  background: blue;
  /* overflow: hidden; */
  color: white;
  vertical-align:top;
}

Upvotes: 0

Related Questions