Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colour only one part of an HTML element

Tags:

javascript

css

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.

like image 579
sites Avatar asked Dec 28 '12 17:12

sites


2 Answers

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:

demo

JSFiddle demo

like image 135
h2ooooooo Avatar answered Sep 30 '22 11:09

h2ooooooo


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;
}
like image 29
techfoobar Avatar answered Sep 30 '22 10:09

techfoobar