auto auto - 1 year ago 85
CSS Question

Change width of div without affecting contents inside

I would like to create a set of svg images and place it in a div. When that div gets resized (in javascript), I want the width to change, without changing what's inside it, giving the effect of the resized div covering up the contents (ex. cutting the div's width in half will make half the content inside hidden).

Is this possible through html?

Here is a js fiddle. When you push the button, the div width changes to a smaller size. I want it to hide the portion of the svg outside of it.

<div id="container">

<svg width="400" height="280">
<rect x="50" y="20" rx="20" ry="20" width="150" height="150" style="fill:red;stroke:black;stroke-width:5;opacity:0.5"></rect>

<rect x="90" y="50" rx="20" ry="20" width="150" height="150" style="fill:blue;stroke:black;stroke-width:5;opacity:0.5"></rect>


Answer Source

This is a quick fix with just CSS, no JavaScript needed. You can hide what "overflows" with the overflow property.

Add overflow hidden to #container:

    overflow: hidden;

You can try this again with your fiddle modified

Also, there are a couple of other things going on in your fiddle: You are not using == in your conditional statements. And even if you were, you need a way to start things off with a dynamic width. So, here's a fixed up fiddle that uses just the JS changes.

Lastly, I would do it slightly different in the way that I would add / remove classes based on if that class is already added to that element. You can check that out here on this fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download