Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing images and text to be selected

Tags:

html

css

I have an image being hacked in as a background image (as shown here). I've noticed that if I drag my mouse over it though, it selected the image so that it can't be deselected. I've tried the following code to no avail:

    <style type="text/css">
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        img#bg {
            position:fixed;
            top:0;
            left:0;
            width:100%;
            height:100%;
        }
        #content {
            position:relative;
            z-index:1;
            top:0px;
            left:0px;
        }
        *.unselectable {
            -moz-user-select: -moz-none;
            -khtml-user-select: none;
            -webkit-user-select: none;
            -o-user-select: none;
            user-select: none;
        }
    </style>

Any ideas?

like image 936
Freesnöw Avatar asked May 06 '11 17:05

Freesnöw


People also ask

How do I stop selecting text?

You can use the user-select property to disable text selection of an element. In web browsers, if you double-click on some text it will be selected/highlighted. This property can be used to prevent this.

How do you make an image not selectable in HTML?

Learn HTML The user select property can be used to prevent this. By setting this property to none, we can prevent our image from being selected (highlighted).

How do you stop highlighting text when clicking in CSS?

Use the user-select: none; CSS rule.

How do you make an image not Highlightable in CSS?

Reliable Pure CSS Solutionpointer-events: none; user-select: none; This works reliably across all modern browsers.


1 Answers

Add this to your style sheet

.selectDisable {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
}

.selectEnable { 
    -webkit-user-select: text;
    -khtml-user-select: text;
    -moz-user-select: text;
    -o-user-select: text;
    user-select: text;
}

Just add the class selectDisable to the element you want to prevent from being selected.

The drag effect occurs on webkit(chrome, safari, opera). It does not happen on Firefox.

Don't this apply to your whole document if you have textual content because then you won't be able to select text, which is not very user-friendly.

You could also prevent dragging by adding another empty div on top of your image with the same selectDisable class.

Here is a working example:
http://jsfiddle.net/xugy6shd/3/

like image 137
Piotr Kula Avatar answered Oct 08 '22 04:10

Piotr Kula