How would I go about coloring only one part of an HTML element with something like background-clip
- using CSS only.
I'm looking something like:
div {
background-image: url('mi_image');
***: 50% 30em; /* Background only covering 50% height and 30em width */
}
I'm also open to a JavaScript solution, if necessary - but pure CSS would be better.
I'd create a background div. Consider this HTML:
<div id="outer-container">
<div id="container-background"></div>
<div id="container">
<p>
Here's some of my interesting text
</p>
</div>
</div>
With this CSS:
<style type="text/css">
#outer-container {
height: 300px;
width: 300px;
border: 1px solid black;
position: relative;
overflow: hidden;
}
#container-background {
position: absolute;
top: 0px;
left: 0px;
background-color: #FF0000; /* Use background-image or whatever suits you here */
width: 50%; /* Your width */
height: 200px; /* Your height */
z-index: -1;
}
</style>
To create a result like this:
JSFiddle demo
You can color part of the element's background using the pseudo :before
element.
Demo: http://jsfiddle.net/yw3wF/
Code:
<div class="foo">This is the element. This is the element. This is the element. This is the element. This is the element. This is the element. This is the element. This is the element. This is the element. This is the element. </div>
.foo {
width: 200px;
height: 200px;
position: relative;
border: 1px solid green;
margin: 10px;
float: left;
}
.foo:before {
content: "";
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 50%;
background-color: yellow;
z-index: -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With