Search code examples
csshtmlposition

How to hide half a div on top inside of another div?


How do I write the css to do the below effect?

My current setting is outer div position: relative, inner div position: absolute. Didn't work.

Please advise. Thank you very much.

    ------------
    |//////////|
    |//////////|  <= hidden
--------------------
|   |          |   |
|   | inner div|   |
|   |          |   |
|   ------------   |
|                  |
|                  |
|                  |
|                  |
--------------------

Solution

  • Your code is quite nearly there. What you need to do is set the overflow property on the parent to be hidden. By default, your browser will set it to visible, which makes it so that anything that sticks out the sides of your element will be shown, as you've seen.

    Here's some code that shows overflow: hidden at work. View it on JSFiddle.

    html

    ​<div id="parent">
      <div>
      </div>
    </div>​​​​
    

    css

    ​​#parent {
      width: 100px;
      height: 100px;
      position: relative;
      top: 50px;
      left: 50px;
      background: #eee;
      overflow-y: hidden;
    }
    #parent > div {
      position: absolute;
      width: 50px;
      height: 50px;
      top: -25px;
      left: 25px;
      background: #555;
    }
    

    ​ A point to note is that, in this example, I've just hidden the overflow in the vertical direction. You can set it in both, or just horizontally or just vertically. It's pretty neat stuff.

    Interested in learning more about overflow? My man Chris Coyier has an excellent article about it. You should give it a read-through sometime.