Vikas Kumar
Vikas Kumar

Reputation: 739

Why is overflow: hidden not working on my div?

If you try to give margin-left to C1 div, it moves and overflow is hidden. But if you try to give margin-left to C2 div, it moves towards right, but overflow is not hidden, rather it moves in next line (behavior of inline-block).

So why is it not working on C2 div? Is there any way to solve this problem?

(Basically I want C1 and C2 div to be placed together and overflow should be hidden if I increase their widths, or if I give them margins).

Here's what I'm trying:

.c1 {
  width: 220px;
  height: 200px;
  background-color: #666666;
  display: inline-block;
}
.c2 {
  width: 200px;
  height: 220px;
  background-color: #CCCCCC;
  display: inline-block;
}
.c3 {
  width: 180px;
  height: 210px;
  background-color: #333333;
  display: block;
}
.wrapper {
  background-color: red;
  width: 500px;
  height: 500px;
  display: inline-block;
  overflow: hidden;
}
<div class="wrapper">
  <div class="c1">C1</div>
  <div class="c2">C2</div>
  <div class="c3">C3</div>
</div>

Upvotes: 13

Views: 24328

Answers (2)

Ashish Talreja
Ashish Talreja

Reputation: 156

Don't use the display property, use the float property. For example:

.c1 {
    width: 220px;
    height: 200px;
    background-color: #666666;
    float: left;
    margin-left: 10px;
    overflow: hidden;
}
.c2 {
    width: 200px;
    height: 220px;
    background-color: #cccccc;
    float: left;
    margin-left: 10px;
    overflow: hidden;
}
.c3 {
    width: 180px;
    height: 210px;
    background-color: #333333;
    float: left;
    margin-left: 10px;
    overflow: hidden;
}
.wrapper {
    background-color: red;
    width: 500px;
    height: 500px;
    display: inline-block;
    overflow: hidden;
}
<div class="wrapper">
    <div class="c1">C1</div>
    <div class="c2">C2</div>
    <div class="c3">C3</div>
</div>

Upvotes: 0

Michael Benjamin
Michael Benjamin

Reputation: 371003

Add white-space: nowrap to the container (.wrapper).

white-space

The white-space property is used to describe how whitespace inside the element is handled.

nowrap

Collapses whitespace as for normal, but suppresses line breaks (text wrapping) within text.

source: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

To understand why, with white-space: normal, C2 wraps but C1 does not, see these posts:

Here's an excerpt from an answer by @BoltClock:

  • The value of overflow on a container doesn't influence whether or when its contents overflow; it only changes how it and its contents are rendered, when overflow does occur.

  • So you have to force the inline-blocks to actually overflow the container.

  • Since an inline-block has the same rigid physical structure as a block container box, it's impossible for an inline-block to "break apart" or wrap when it's the only inline-level box on a given line box.

Upvotes: 14

Related Questions