I have not had much success finding how to style Google's new recaptcha (v2). The eventual goal is to make it responsive, but I am having difficulty applying styling for even simple things like width.
Their API documentation does not appear to give any specifics on how to control styling at all other than the theme parameter, and simple CSS & JavaScript solutions haven't worked for me.
Basically, I need to be able to apply CSS to Google's new version of reCaptcha. Using JavaScript with it is acceptable.
Overview:
Sorry to be the answerer of bad news, but after research and debugging, it's pretty clear that there is no way to customize the styling of the new reCAPTCHA controls. The controls are wrapped in an iframe, which prevents the use of CSS to style them, and Same-Origin Policy prevents JavaScript from accessing the contents, ruling out even a hacky solution.
Why No Customize API?:
Unlike reCAPTCHA API Version 1.0, there are no customize options in API Version 2.0. If we consider how this new API works, it's no surprise why.
Excerpt from Are you a robot? Introducing “No CAPTCHA reCAPTCHA”:
While the new reCAPTCHA API may sound simple, there is a high degree of sophistication behind that modest checkbox. CAPTCHAs have long relied on the inability of robots to solve distorted text. However, our research recently showed that today’s Artificial Intelligence technology can solve even the most difficult variant of distorted text at 99.8% accuracy. Thus distorted text, on its own, is no longer a dependable test.
To counter this, last year we developed an Advanced Risk Analysis backend for reCAPTCHA that actively considers a user’s entire engagement with the CAPTCHA—before, during, and after—to determine whether that user is a human. This enables us to rely less on typing distorted text and, in turn, offer a better experience for users. We talked about this in our Valentine’s Day post earlier this year.
If you were able to directly manipulate the styling of the control elements, you could easily interfere with the user-profiling logic that makes the new reCAPTCHA possible.
What About a Custom Theme?:
Now the new API does offer a theme option, by which you can choose a preset theme such as light and dark. However there is not presently a way to create a custom theme. If we inspect the iframe, we will find the theme name is passed in the query string of the src attribute. This URL looks something like the following.
https://www.google.com/recaptcha/api2/anchor?...&theme=dark&...
This parameter determines what CSS class name is used on the wrapper element in the iframe and determines the preset theme to use.
Digging through the minified source, I found that there are actually 4 valid theme values, which is more than the 2 listed in the documentation, but default and standard are the same as light.
We can see the code that selects the class name from this object here.
There is no code for a custom theme, and if any other theme value is specified, it will use the standard theme.
In Conclusion:
At present, there is no way to fully style the new reCAPTCHA elements, only the wrapper elements around the iframe can be stylized. This was almost-certainly done intentionally, to prevent users from breaking the user profiling logic that makes the new captcha-free checkbox possible. It is possible that Google could implement a limited custom theme API, perhaps allowing you to choose custom colors for existing elements, but I would not expect Google to implement full CSS styling.
As guys mentioned above, there is no way ATM. but still if anyone interested, then by adding in just two lines you can at least make it look reasonable, if it break on any screen. you can assign different value in #media query.
<div id="recaptchaContainer" style="transform:scale(0.8);transform-origin:0 0"></div>
Hope this helps anyone :-).
I use below trick to make it responsive and remove borders. this tricks maybe hide recaptcha message/error.
This style is for rtl lang but you can change it easy.
.g-recaptcha {
position: relative;
width: 100%;
background: #f9f9f9;
overflow: hidden;
}
.g-recaptcha > * {
float: right;
right: 0;
margin: -2px -2px -10px;/*remove borders*/
}
.g-recaptcha::after{
display: block;
content: "";
position: absolute;
left:0;
right:150px;
top: 0;
bottom:0;
background-color: #f9f9f9;
clear: both;
}
<div class="g-recaptcha" data-sitekey="Your Api Key"></div>
<script src='https://www.google.com/recaptcha/api.js?hl=fa'></script>
Unfortunately we cant style reCaptcha v2, but it is possible to make it look better, here is the code:
Click here to preview
.g-recaptcha-outer{
text-align: center;
border-radius: 2px;
background: #f9f9f9;
border-style: solid;
border-color: #37474f;
border-width: 1px;
border-bottom-width: 2px;
}
.g-recaptcha-inner{
width: 154px;
height: 82px;
overflow: hidden;
margin: 0 auto;
}
.g-recaptcha{
position:relative;
left: -2px;
top: -1px;
}
<div class="g-recaptcha-outer">
<div class="g-recaptcha-inner">
<div class="g-recaptcha" data-size="compact" data-sitekey="YOUR KEY"></div>
</div>
</div>
Add a data-size property to the google recaptcha element and make it equal to "compact" in case of mobile.
Refer: google recaptcha docs
What you can do is to hide the ReCaptcha Control behind a div. Then make your styling on this div. And set the css "pointer-events: none" on it, so you can click through the div (Click through a DIV to underlying elements).
The checkbox should be in a place where the user is clicking.
You can recreate recaptcha , wrap it in a container and only let the checkbox visible. My main problem was that I couldn't take the full width so now it expands to the container width. The only problem is the expiration you can see a flick but as soon it happens I reset it.
See this demo http://codepen.io/alejandrolechuga/pen/YpmOJX
function recaptchaReady () {
grecaptcha.render('myrecaptcha', {
'sitekey': '6Lc7JBAUAAAAANrF3CJaIjt7T9IEFSmd85Qpc4gj',
'expired-callback': function () {
grecaptcha.reset();
console.log('recatpcha');
}
});
}
.recaptcha-wrapper {
height: 70px;
overflow: hidden;
background-color: #F9F9F9;
border-radius: 3px;
box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);
-webkit-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);
-moz-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);
height: 70px;
position: relative;
margin-top: 17px;
border: 1px solid #d3d3d3;
color: #000;
}
.recaptcha-info {
background-size: 32px;
height: 32px;
margin: 0 13px 0 13px;
position: absolute;
right: 8px;
top: 9px;
width: 32px;
background-image: url(https://www.gstatic.com/recaptcha/api2/logo_48.png);
background-repeat: no-repeat;
}
.rc-anchor-logo-text {
color: #9b9b9b;
cursor: default;
font-family: Roboto,helvetica,arial,sans-serif;
font-size: 10px;
font-weight: 400;
line-height: 10px;
margin-top: 5px;
text-align: center;
position: absolute;
right: 10px;
top: 37px;
}
.rc-anchor-checkbox-label {
font-family: Roboto,helvetica,arial,sans-serif;
font-size: 14px;
font-weight: 400;
line-height: 17px;
left: 50px;
top: 26px;
position: absolute;
color: black;
}
.rc-anchor .rc-anchor-normal .rc-anchor-light {
border: none;
}
.rc-anchor-pt {
color: #9b9b9b;
font-family: Roboto,helvetica,arial,sans-serif;
font-size: 8px;
font-weight: 400;
right: 10px;
top: 53px;
position: absolute;
a:link {
color: #9b9b9b;
text-decoration: none;
}
}
g-recaptcha {
// transform:scale(0.95);
// -webkit-transform:scale(0.95);
// transform-origin:0 0;
// -webkit-transform-origin:0 0;
}
.g-recaptcha {
width: 41px;
/* border: 1px solid red; */
height: 38px;
overflow: hidden;
float: left;
margin-top: 16px;
margin-left: 6px;
> div {
width: 46px;
height: 30px;
background-color: #F9F9F9;
overflow: hidden;
border: 1px solid red;
transform: translate3d(-8px, -19px, 0px);
}
div {
border: 0;
}
}
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaReady&&render=explicit'></script>
<div class="recaptcha-wrapper">
<div id="myrecaptcha" class="g-recaptcha"></div>
<div class="rc-anchor-checkbox-label">I'm not a Robot.</div>
<div class="recaptcha-info"></div>
<div class="rc-anchor-logo-text">reCAPTCHA</div>
<div class="rc-anchor-pt">
Privacy
<span aria-hidden="true" role="presentation"> - </span>
Terms
</div>
</div>
Great!
Now here is styling available for reCaptcha..
I just use inline styling like:
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXX" style="transform: scale(1.08); margin-left: 14px;"></div>
whatever you wanna to do small customize in inline styling...
Hope it will help you!!
I came across this answer trying to style the ReCaptcha v2 for a site that has a light and a dark mode. Played around some more and discovered that besides transform, filter is also applied to iframe elements so ended up using the default/light ReCaptcha and doing this when the user is in dark mode:
.g-recaptcha {
filter: invert(1) hue-rotate(180deg);
}
The hue-rotate(180deg) makes it so that the logo is still blue and the check-mark is still green when the user clicks it, while keeping white invert()'ed to black and vice versa.
Didn't see this in any answer or comment so decided to share even if this is an old thread.
Just adding a hack-ish solution to make it responsive.
Wrap the recaptcha in an extra div:
<div class="recaptcha-wrap">
<div id="g-recaptcha"></div>
</div>
Add styles. This assumes the dark theme.
// Recaptcha
.recaptcha-wrap {
position: relative;
height: 76px;
padding:1px 0 0 1px;
background:#222;
> div {
position: absolute;
bottom: 2px;
right:2px;
font-size:10px;
color:#ccc;
}
}
// Hides top border
.recaptcha-wrap:after {
content:'';
display: block;
background-color: #222;
height: 2px;
width: 100%;
top: -1px;
left: 0px;
position: absolute;
}
// Hides left border
.recaptcha-wrap:before {
content:'';
display: block;
background-color: #222;
height: 100%;
width: 2px;
top: 0;
left: -1px;
position: absolute;
z-index: 1;
}
// Makes it responsive & hides cut-off elements
#g-recaptcha {
overflow: hidden;
height: 76px;
border-right: 60px solid #222222;
border-top: 1px solid #222222;
border-bottom: 1px solid #222;
position: relative;
box-sizing: border-box;
max-width: 294px;
}
This yields the following:
It will now resize horizontally, and doesn't have a border. The recaptcha logo would get cut off on the right, so I am hiding it with a border-right. It's also hiding the privacy and terms links, so you may want to add those back in.
I attempted to set a height on the wrapper element, and then vertically center the recaptcha to reduce the height. Unfortunately, any combo of overflow:hidden and a smaller height seems to kill the iframe.
in the V2.0 it's not possible. The iframe blocks all styling out of this. It's difficult to add a custom theme instead of the dark or light one.
Late to the party, but maybe my solution will help somebody.
I haven't found any solution that works on a responsive website when the viewport changes or the layout is fluid.
So I've created a jQuery script for django-cms that is dynamically adapting to a changing viewport.
I'm going to update this response as soon as I have the need for a modern variant of it that is more modular and has no jQuery dependency.
html
<div class="g-recaptcha" data-sitekey="{site_key}" data-size={size}>
</div>
css
.g-recaptcha { display: none; }
.g-recaptcha.g-recaptcha-initted {
display: block;
overflow: hidden;
}
.g-recaptcha.g-recaptcha-initted > * {
transform-origin: top left;
}
js
window.djangoReCaptcha = {
list: [],
setup: function() {
$('.g-recaptcha').each(function() {
var $container = $(this);
var config = $container.data();
djangoReCaptcha.init($container, config);
});
$(window).on('resize orientationchange', function() {
$(djangoReCaptcha.list).each(function(idx, el) {
djangoReCaptcha.resize.apply(null, el);
});
});
},
resize: function($container, captchaSize) {
scaleFactor = ($container.width() / captchaSize.w);
$container.find('> *').css({
transform: 'scale(' + scaleFactor + ')',
height: (captchaSize.h * scaleFactor) + 'px'
});
},
init: function($container, config) {
grecaptcha.render($container.get(0), config);
var captchaSize, scaleFactor;
var $iframe = $container.find('iframe').eq(0);
$iframe.on('load', function() {
$container.addClass('g-recaptcha-initted');
captchaSize = captchaSize || { w: $iframe.width() - 2, h: $iframe.height() };
djangoReCaptcha.resize($container, captchaSize);
djangoReCaptcha.list.push([$container, captchaSize]);
});
},
lateInit: function(config) {
var $container = $('.g-recaptcha.g-recaptcha-late').eq(0).removeClass('.g-recaptcha-late');
djangoReCaptcha.init($container, config);
}
};
window.djangoReCaptchaSetup = window.djangoReCaptcha.setup;
With the integration of the invisible reCAPTCHA you can do the following:
To enable the Invisible reCAPTCHA, rather than put the parameters in a div, you can add them directly to an html button.
a. data-callback=””. This works just like the checkbox captcha, but is required for invisible.
b. data-badge: This allows you to reposition the reCAPTCHA badge (i.e. logo and
‘protected by reCAPTCHA’ text) . Valid options as ‘bottomright’ (the default),
‘bottomleft’ or ‘inline’ which will put the badge directly above the button. If you
make the badge inline, you can control the CSS of the badge directly.
In case someone struggling with the recaptcha of contact form 7 (wordpress) here is a solution working for me
.wpcf7-recaptcha{
clear: both;
float: left;
}
.wpcf7-recaptcha{
margin-right: 6px;
width: 206px;
height: 65px;
overflow: hidden;
border-right: 1px solid #D3D3D3;
}
.wpcf7-recaptcha iframe{
padding-bottom: 15px;
border-bottom: 1px solid #D3D3D3;
background: #F9F9F9;
border-left: 1px solid #d3d3d3;
}
if you use scss, that worked for me:
.recaptcha > div{
transform: scale(0.84);
transform-origin: 0;
}
If someone is still interested, there is a simple javascript library (no jQuery dependency), named custom recaptcha. It lets you customize the button with css and implement some js events (ready/checked). The idea is to make the default recaptcha "invisible" and put a button over it. Just change the id of the recaptcha and that's it.
<head>
<script src="https://azentreprise.org/download/custom-recaptcha.min.js"></script>
<style type="text/css">
#captcha {
float: left;
margin: 2%;
background-color: rgba(72, 61, 139, 0.5); /* darkslateblue with 50% opacity */
border-radius: 2px;
font-size: 1em;
color: #C0FFEE;
}
#captcha.success {
background-color: rgba(50, 205, 50, 0.5); /* limegreen with 50% opacity */
color: limegreen;
}
</style>
</head>
<body>
<div id="captcha" data-sitekey="your_site_key" data-label="Click here" data-label-spacing="15"></div>
</body>
See https://azentreprise.org/read.php?id=1 for more information.
I am just adding this kind of solution / quick fix so it won't get lost in case of a broken link.
Link to this solution "Want to add link How to resize the Google noCAPTCHA reCAPTCHA | The Geek Goddess" was provided by Vikram Singh Saini and simply outlines that you could use inline CSS to enforce framing of the iframe.
// Scale the frame using inline CSS
<div class="g-recaptcha" data-theme="light"
data-sitekey="XXXXXXXXXXXXX"
style="transform:scale(0.77);
-webkit-transform:scale(0.77);
transform-origin:0 0;
-webkit-transform-origin:0 0;
">
</div>
// Scale the images using a stylesheet
<style>
#rc-imageselect, .g-recaptcha {
transform:scale(0.77);
-webkit-transform:scale(0.77);
transform-origin:0 0;
-webkit-transform-origin:0 0;
}
</style>
You can use some CSS for Google reCAPTCHA v2 styling on your website:
– Change background, color of Google reCAPTCHA v2 widget:
.rc-anchor-light {
background: #fff!important;
color: #fff!important; }
or
.rc-anchor-normal{
background: #000 !important;
color: #000 !important; }
– Resize the Google reCAPTCHA v2 widget by using this snippet:
.rc-anchor-light {
transform:scale(0.9);
-webkit-transform:scale(0.9); }
– Responsive your Google reCAPTCHA v2:
#media only screen and (min-width: 768px) {
.rc-anchor-light {
transform:scale(0.85);
-webkit-transform:scale(0.85); }
}
All elements, property of CSS above that’s just for your reference. You can change them by yourself (only using CSS class selector).
Refer on OIW Blog - How To Edit CSS of Google reCAPTCHA (Re-style, Change Position, Resize reCAPTCHA Badge)
You can also find out Google reCAPTCHA v3's styling there.
A bit late but I tried this and it worked to make the Recaptcha responsive on screens smaller than 460px width. You can't use css selector to select elements inside the iframe. So, better use the outermost parent element which is the class g-recaptcha to basically zoom-out i.e transform the size of the entire container. Here's my code which worked:
#media(max-width:459.99px) {
.modal .g-recaptcha {
transform:scale(0.75);
-webkit-transform:scale(0.75); }
}
}
Incase someone wants to resize recaptcha for small devices.
I was using recaptcha V2 with primeng p-captcha (for angular). The issue was that for smaller screens it would go out of the screen.
Although you can't actually resize it (the external thing and all everyone has explained it above) but there is a way with transform property (scaling the the container)
this was my code below the way, I achieved it
p-captcha div div {
transform:scale(0.9) !important;
-webkit-transform:scale(0.9) !important;
transform-origin:0 0 !important;
-webkit-transform-origin:0 0 !important;
}
Other than p-captcha you can use this code snippet below
.g-recaptcha {
transform:scale(0.9);
transform-origin:0 0;
}
Before
After
Topic is old, but I also wanted to scale the reCAPTCHA widget -- but to make it bigger for phone users, unlike many others who wanted it smaller. The only way that worked was transform: scale(x), but that seemed to make the widget too wide for my page, thus shrinking the rest of the form on the page. Using a container div as shown below fixed my problem, and hopefully it will help someone else who thinks a bigger version is better on a small screen.
<style>
:root {
/* factor to scale the Google widget in potrait mode (on a phone) */
--recaptcha-scale: 2;
}
#media screen and (orientation: portrait) {
/* needed to rein in the width of inner div when it is scaled */
#g_recaptcha_div_container {
width: calc(100vmin / var(--recaptcha-scale));
}
#g_recaptcha_div {
transform: scale(var(--recaptcha-scale));
transform-origin: 0 0;
}
#submit_button {
width: 65vmin;
height: 9vmin;
font-size: 7vmin;
/* needed to scoot the button out from under the scaled div */
margin-top: 10vmin;
}
}
</style>
<html>
<!-- top of form with a bunch of fields to create an acct -->
<div id="g_recaptcha_div_container">
<div id="g_recaptcha_div" class="g-recaptcha" data-sitekey="foo">
</div>
</div>
<input id="submit_button" type="submit" value="Create Account">
<!-- bottom of form -->
</html>
You can try to color it with this css filter hack:
.colorize-pink {
filter: brightness(0.5) sepia(1) hue-rotate(-70deg) saturate(5);
}
.colorize-navy {
filter: brightness(0.2) sepia(1) hue-rotate(180deg) saturate(5);
}
and for the size, use transform css hack
.captcha-size {
transform:scale(0.8);transform-origin:0 0
}
Lets play a little with JavaScript:
First at all, we know that recaptcha badget include all the shit from the most crazy people on Google, so you can only make changes with theme "dark" and "light" on your web.
Take a look to my website
SantiagoSoñora.
let recaptcha = document.querySelector('.g-recaptcha');
With this, you only can touch simple settings of the badge, like z-index and size, but no much more...
So far, i made two functions that set data-theme to light or dark mode at innit. Note that its neccessary assign the "light" because Google not include that by default.
function reCaptchaDark() {
document.addEventListener('DOMContentLoaded', (event) => {
recaptcha.setAttribute("data-theme", "dark");
})
}
function reCaptchaLight() {
document.addEventListener('DOMContentLoaded', (event) => {
recaptcha.setAttribute("data-theme", "light");
})
}
Then, for example, my web looks if user prefers a dark or a light theme, and set that configurations to the recaptcha bag:
(theme.onLoad = function() {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
reCaptchaDark();
toggleTheme();
}
else {
reCaptchaLight();
}
})();
Note that my code for toggle from dark to light is on the toggleTheme() function.
Keep doing magic: You should configure a class on the html tag or something else on your web for made the change between dark and light theme, and with that we now modify the src on the iframe so when we toggle dark/light mode ,with our button it changes:
theme.onclick = function() {
toggleTheme();
if (html.classList.contains('dark')) {
recaptcha.setAttribute("data-theme", "dark");
setTimeout(function() {
let iframes = document.querySelectorAll('iframe');
iframes[0].src = iframes[0].src.replace('&theme=light', '&theme=dark');
}, 0);
}
else {
recaptcha.setAttribute("data-theme", "light");
setTimeout(function() {
let iframes = document.querySelectorAll('iframe');
iframes[0].src = iframes[0].src.replace('&theme=dark', '&theme=light');
}, 0);
}
}
And here you go, the recaptcha badge change from dark to light "preassigned" themes by Google bad guys.
And last but not least, a function that updates the page to change if your theme is dark by default.
This update the LocalStorage
(function() {
if( window.localStorage ) {
if( !localStorage.getItem('firstLoad') ) {
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
You can use the class .grecaptcha-badge for some css changes, like opacity and box-shadow, -> (use !important)
Thats all, hope you can implement on your site
I am trying to create a div and show a timeout message in there. But it actually distorts other parts of Page. For eg see below. Session Timed out is the div with the message.
Now I don't want this to happen. PFB the JQuery code I am using to create this Div
function ShowSessionTimeOutDiv() {
var styler = document.createElement("div");
styler.setAttribute("style","font-size:15px;width:auto;height:auto;top:50%;left:40%;color:red;");
styler.innerHTML = "<b><i>Session TimedOut, Please refresh the Page</i></b>";
document.body.appendChild(styler);
var currentDiv = $('#GoToRequestControl1_UpdatePanel1').get(0);
currentDiv.parentNode.insertBefore(styler,currentDiv) ;
}
Am I missing something here? The Part in which this div is being displayed is coming from Master Page.
Have you tried the position:fixed styling on it in css, i did that on one of my websites and it didn't distort anything.
A page has a natural flow of its elements based on the default display rules specified by the W3C. When you add a div in between other elements it naturally affects the layout of the page; the positions of the other elements.
In order to drop in a new element without it affecting other elements you have to either reserve space for it, or take it out of the normal page flow.
There are a couple of ways to take an element out of the flow — you can float it, float:left or float:right, which is great, for example, to stack blocks on the left (instead of top-down) and let them wrap to new rows as available width changes. Using a flex layout gives you a lot of control also. But in this case of one thing popping up, changing the positioning of the new element is the most straightforward and can let you put the block exactly where you want it.
I have a demonstration and full explanation in a fiddle showing several examples along the way to getting what you want.
Basically, styling is needed to reposition the timeout message element that you're inserting. Styling is better done with CSS styles, compared to adding a bunch of inline styles. If I put my timeout popup message in a "messagebox" I can make a class for it.
/* Your styles, plus a couple extra to make the example stand out better */
div.messagebox {
font-size: 16px;
width: auto;
height: auto;
top: 40%;
left: 30%;
background-color: white;
border: 2px solid black;
}
Likewise, style the message itself with a class, instead of using inline styles and the deprecated presentational tags <b> and <i>.
/* I want the message in a messagebox to be bold-italic-red text. */
div.messagebox .message {
color: red;
font-style: italic;
font-weight: bold;
}
The big difference is that we will change the positioning of the element from the default static to instead use absolute positioning:
/* I don't really recommend a class called "positioned".
A class should describe the kind of thing the element *is*
not how it *looks*
*/
div.messagebox.positioned {
position: absolute;
width: 40%;
padding: 1.5em;
}
/* The container of the positioned element also has to be positioned.
We position it "relative" but don't move it from its natural position.
*/
section#hasposition {
position: relative;
}
The term "absolute" is tricky to learn ... the element being positioned is given an absolute position within its container, in a sense it's positioned relative to its container... but what position:relative means is relative to its own natural position, so it's easy to get confused at first over whether you want absolute or relative positioning.
Putting it all together, we have some basic HTML that represents major portions of a page — a real page will have far more, but those should be contained within some top-level containers. This shows only those top-level containers.
Then we have some javascript that will add the new element at the appropriate time. Here I just call the function to add it after a delay created with setTimeout(). I'm using full-on jQuery since you're using some in your example, and it makes the javascript more portable and more concise.
function ShowSessionTimeoutStyled() {
var styler = $('<div>').addClass('messagebox').addClass('positioned');
styler.html('<span class="message">The Session Timed Out</span>');
$('#hasposition .above').after(styler);
}
// wait 6 seconds then add the new div
setTimeout(ShowSessionTimeoutStyled, 6000);
div.messagebox {
font-size: 16px;
width: auto;
height: auto;
top: 20%;
left: 20%;
background-color: white;
border: 2px solid black;
}
div.messagebox .message {
color: red;
font-style: italic;
font-weight: bold;
}
div.messagebox.positioned {
position: absolute;
width: 40%;
padding: 1.5em;
}
section#hasposition {
position: relative;
}
/* also style some of the basic parts so you can see them better in the demonstration */
section.explanation {
margin: 1em 0.5em;
padding: 0.5em;
border: 1px solid gray;
}
.demonstration {
margin-left: 1em;
padding: 1em;
background-color: #e0e0e0;
}
.demonstration .above {
background-color: #fff0f0;
}
.demonstration .middle {
background-color: #f0fff0;
}
.demonstration .below {
background-color: #f0f0ff;
}
.demonstration footer {
background-color: white;
}
p {
margin-top: 0;
padding-top: 0;
}
section {
font-family: sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="explanation">
<p>Here, a div is added dynamically, after the "basic part above", but the added div is <em>positioned</em>. You can see the other content isn't affected.</p>
<section class="demonstration" id="hasposition">
<div class="above">Basic part above</div>
<div class="middle">Middle part</div>
<div class="below">Part Below</div>
<footer>This is the page footer</footer>
</section>
</section>
I highly recommend the site Position Is Everything for articles and tutorials on positioning. Some of its other content is outdated — who needs to make PNGs to do drop-shadows any more? — but the way positioning works hasn't changed.
For an application we're developing at the company where I work, we need an input that supports inserting emoticons inside our JS-based web app. We're currently using an input with the emoticon shortcodes (ie ':-)') and would like to switch to inserting actual, graphical images.
Our original plan was to use a contenteditable <div>. We're using listeners for the paste event as well as the different key/mouse interactions to ensure no unwanted markup enters the contenteditable (we strip text out of its container tags and leave only image tags that we inserted ourselves).
However, the problem right now is that the div resizes if you put in enough content (ie its height increases). We don't want this to happen, nor is it acceptable for the text to just be hidden (ie plain overflow: hidden). So:
Is there a way to make the contenteditable div behave like a single-line input?
I'd like it best if there is a relatively simple attribute/css property that I've missed that will do what I want, but if necessary CSS+JS suggestions will also be appreciated.
[contenteditable="true"].single-line {
white-space: nowrap;
width:200px;
overflow: hidden;
}
[contenteditable="true"].single-line br {
display:none;
}
[contenteditable="true"].single-line * {
display:inline;
white-space:nowrap;
}
<div contenteditable="true" class="single-line">
This should work.
</div>
Other answers are wrong and contain few mistakes (on 2019-05-07). Other solutions suggest to use "white-space: nowrap" (prevents carrying to another line) + "overflow: hidden" (prevents long text going beyond the field) + hiding <br> and other.
First mistake in that solutions is "overflow: hidden" also prevents scrolling the text. User will not be able to scroll the text by:
Pressing mouse middle button
Selecting the text and moving mouse pointer to the left or right
Using horizontal mouse scroll (when user have such a thing)
The only way he can scroll is using keyboard arrows.
You can solve this problem by using "overflow: hidden" and "overflow: auto" (or "scroll") at the same time. You should create parent div with "overflow: hidden" to hide content user should not see. This element must have input borders and other design. And you should create child div with "overflow-x: auto" and "contenteditable" attribute. This element will have scrollbar so user can scroll it without any limitations and he will not see this scrollbar because of hiding overflow in parent element.
Example of solution:
document.querySelectorAll('.CETextInput').forEach(el => {
//Focusing on child element after clicking parent. We need it because parent element has bigger width than child.
el.parentNode.addEventListener('mousedown', function(e) {
if (e.target === this) {
setTimeout(() => this.children[0].focus(), 0);
}
});
//Prevent Enter. See purpose in "Step 2" in answer.
el.parentNode.addEventListener('keydown', function(e) {
if (e.keyCode === 13)
e.preventDefault();
});
});
.CETextInputBorder { /*This element is needed to prevent cursor: text on border*/
display: inline-block;
border: 1px solid #aaa;
}
.CETextInputCont {
overflow: hidden;
cursor: text; /*You must set it because parent elements is bigger then child contenteditable element. Also you must add javascript to focus child element on click parent*/
/*Style:*/
width: 10em;
height: 1em;
line-height: 1em;
padding: 5px;
font-size: 20px;
font-family: sans-serif;
}
.CETextInput {
white-space: pre; /*"pre" is like "nowrap" but displays all spaces correctly (with "nowrap" last space is not displayed in Firefox, tested on Firefox 66, 2019-05-15)*/
overflow-x: auto;
min-height: 100%; /*to prevent zero-height with no text*/
/*We will duplicate vertical padding to let user click contenteditable element on top and bottom. We would do same thing for horizontal padding but it is not working properly (in all browsers when scroll is in middle position and in Firefox when scroll is at the end). You can also replace vertical padding with just bigger line height.*/
padding: 5px 0;
margin-top: -5px;
outline: none; /*Prevent border on focus in some browsers*/
}
<div class="CETextInputBorder">
<div class="CETextInputCont">
<div class="CETextInput" contenteditable></div>
</div>
</div>
Step 2: Solving problem with <br> and other:
Also there is a problem that user or extensions can paste
<br> (can be pasted by user)
<img> (may have big size) (can be pasted by user)
elements with another "white-space" value
<div> and other elements that carry text to another line
elements with unsuitable "display" value
But advise to hide all <br> is wrong too. That is because Mozilla Firefox adds <br> element to empty field (I guess it may be workaround of bug with text cursor disappearing after deleting last character; checked in Firefox 66 released on 2019-03-19). If you hide this element then when user moves focus to field caret will be set in this hidden <br> element and text cursor will be hidden too (always).
You can fix this if you will be <br> when you know field is empty. You need some javascript here (you cannot use :empty selector because field contains <br> elements and not empty). Example of solution:
document.querySelectorAll('.CETextInput').forEach(el => {
//OLD CODE:
//Focusing on child element after clicking parent. We need it because parent element has bigger width than child.
el.parentNode.addEventListener('mousedown', function(e) {
if (e.target === this) {
setTimeout(() => this.children[0].focus(), 0);
}
});
//Prevent Enter to prevent blur on Enter
el.parentNode.addEventListener('keydown', function(e) {
if (e.keyCode === 13)
e.preventDefault();
});
//NEW CODE:
//Update "empty" class on all "CETextInput" elements:
updateEmpty.call(el); //init
el.addEventListener('input', updateEmpty);
function updateEmpty(e) {
const s = this.innerText.replace(/[\r\n]+/g, ''); //You must use this replace, see explanation below in "Step 3"
this.classList.toggle('empty', !s);
}
});
/*OLD CODE:*/
.CETextInputBorder { /*This element is needed to prevent cursor: text on border*/
display: inline-block;
border: 1px solid #aaa;
}
.CETextInputCont {
overflow: hidden;
cursor: text; /*You must set it because parent elements is bigger then child contenteditable element. Also you must add javascript to focus child element on click parent*/
/*Style:*/
width: 10em;
height: 1em;
line-height: 1em;
padding: 5px;
font-size: 20px;
font-family: sans-serif;
}
.CETextInput {
white-space: pre; /*"pre" is like "nowrap" but displays all spaces correctly (with "nowrap" last space is not displayed in Firefox, tested on Firefox 66, 2019-05-15)*/
overflow-x: auto;
min-height: 100%; /*to prevent zero-height with no text*/
/*We will duplicate vertical padding to let user click contenteditable element on top and bottom. We would do same thing for horizontal padding but it is not working properly (in all browsers when scroll is in middle position and in Firefox when scroll is at the end). You can also replace vertical padding with just bigger line height.*/
padding: 5px 0;
margin-top: -5px;
outline: none; /*Prevent border on focus in some browsers*/
}
/*NEW CODE:*/
.CETextInput:not(.empty) br,
.CETextInput img { /*We hide <img> here. If you need images do not hide them but set maximum height. User can paste image by pressing Ctrl+V or Ctrl+Insert.*/
display: none;
}
.CETextInput * {
display: inline;
white-space: pre;
}
<!--OLD CODE:-->
<div class="CETextInputBorder">
<div class="CETextInputCont">
<div class="CETextInput" contenteditable></div>
</div>
</div>
Step 3: Solving problem with getting value:
We hided <br> elements so "innerText" value will not contain them. But:
When "empty" class is set result may contain <br> elements.
Your other styles or extensions may override "display: none" by "!important" mark or by rule with higher priority.
So when you get value you should make replace to avoid accidental getting line breaks:
s = s.replace(/[\r\n]+/g, '');
Do not use javascript for hiding <br>
Also you could solve the problem with <br> by removing them by javascript but this is very bad solution because after every removing user cannot use "undo" action anymore for canceling changes was made before removing.
Also you could use document.execCommand('delete') to delete <br> but it is hard to implement + user can undo your deletion and restore <br> elements.
Adding placeholder
It was not asked in question but I guess many people using single-line contenteditable elements will need it. Here is example how to make placeholder using css and "empty" class we talked above:
//OLD CODE:
document.querySelectorAll('.CETextInput').forEach(el => {
//Focusing on child element after clicking parent. We need it because parent element has bigger width than child.
el.parentNode.addEventListener('mousedown', function(e) {
if (e.target === this) {
setTimeout(() => this.children[0].focus(), 0);
}
});
//Prevent Enter to prevent blur on Enter
el.parentNode.addEventListener('keydown', function(e) {
if (e.keyCode === 13)
e.preventDefault();
});
//Update "empty" class on all "CETextInput" elements:
updateEmpty.call(el); //init
el.addEventListener('input', updateEmpty);
function updateEmpty(e) {
const s = this.innerText.replace(/[\r\n]+/g, ''); //You must use this replace, see explanation below in "Step 3"
this.classList.toggle('empty', !s);
//NEW CODE:
//Make element always have <br>. See description in html. I guess it is not needed because only Firefox has bug with bad cursor position but Firefox always adds this element by itself except on init. But on init we are adding it by ourselves (see html).
if (!s && !Array.prototype.filter.call(this.children, el => el.nodeName === 'BR').length)
this.appendChild(document.createElement('br'));
}
});
/*OLD CODE:*/
.CETextInputBorder { /*This element is needed to prevent cursor: text on border*/
display: inline-block;
border: 1px solid #aaa;
}
.CETextInputCont {
overflow: hidden;
cursor: text; /*You must set it because parent elements is bigger then child contenteditable element. Also you must add javascript to focus child element on click parent*/
/*Style:*/
width: 10em;
height: 1em;
line-height: 1em;
padding: 5px;
font-size: 20px;
font-family: sans-serif;
}
.CETextInput {
white-space: pre; /*"pre" is like "nowrap" but displays all spaces correctly (with "nowrap" last space is not displayed in Firefox, tested on Firefox 66, 2019-05-15)*/
overflow-x: auto;
min-height: 100%; /*to prevent zero-height with no text*/
/*We will duplicate vertical padding to let user click contenteditable element on top and bottom. We would do same thing for horizontal padding but it is not working properly (in all browsers when scroll is in middle position and in Firefox when scroll is at the end). You can also replace vertical padding with just bigger line height.*/
padding: 5px 0;
margin-top: -5px;
outline: none; /*Prevent border on focus in some browsers*/
}
.CETextInput:not(.empty) br,
.CETextInput img { /*We hide <img> here. If you need images do not hide them but set maximum height. User can paste image by pressing Ctrl+V or Ctrl+Insert.*/
display: none;
}
.CETextInput * {
display: inline;
white-space: pre;
}
/*NEW CODE:*/
.CETextInput[placeholder].empty::before { /*Use ::before not ::after or you will have problems width first <br>*/
content: attr(placeholder);
display: inline-block;
width: 0;
white-space: nowrap;
pointer-events: none;
cursor: text;
color: #b7b7b7;
padding-top: 8px;
margin-top: -8px;
}
<!--OLD CODE:-->
<div class="CETextInputBorder">
<div class="CETextInputCont">
<div class="CETextInput" placeholder="Type something here" contenteditable><br></div>
</div>
</div>
<!--We manually added <br> element for Firefox browser because Firefox (tested on 2019-05-11, Firefox 66) has bug with bad text cursor position in empty contenteditable elements that have ::before or ::after pseudo-elements.-->
Solution with only one div and "scrollbar-width"
You can also use only one div by setting "overflow-x: auto", "overflow-y: hidden" and "scrollbar-width: none". But "scrollbar-width" is new property and works only in Firefox 64+ and no other browsers yet.
You can also add:
webkit-prefixed version: "-webkit-scrollbar-width: none"
non-standardized ".CETextInput::-webkit-scrollbar { display: none; }" (for webkit-based browsers)
"-ms-overflow-style: none"
I would not recommend to use this solution, but here is example:
//OLD CODE:
document.querySelectorAll('.CETextInput').forEach(el => {
//Focusing on child is not needed anymore
//Prevent Enter to prevent blur on Enter
el.addEventListener('keydown', function(e) {
if (e.keyCode === 13)
e.preventDefault();
});
//Update "empty" class on all "CETextInput" elements:
updateEmpty.call(el); //init
el.addEventListener('input', updateEmpty);
function updateEmpty(e) {
const s = this.innerText.replace(/[\r\n]+/g, ''); //You must use this replace, see explanation below in "Step 3"
this.classList.toggle('empty', !s);
}
});
/*NEW CODE:*/
.CETextInput {
white-space: pre; /*"pre" is like "nowrap" but displays all spaces correctly (with "nowrap" last space is not displayed in Firefox, tested on Firefox 66, 2019-05-15)*/
overflow-x: auto; /*or "scroll"*/
overflow-y: hidden;
-webkit-scrollbar-width: none; /*Chrome 4+ (probably), webkit based*/
scrollbar-width: none; /*FF 64+, Chrome ??+, webkit based, Edge ??+*/
-ms-overflow-style: none; /*IE ??*/
/*Style:*/
width: 10em;
height: 1em;
line-height: 1em;
padding: 5px;
border: 1px solid #aaa;
font-size: 20px;
font-family: sans-serif;
}
.CETextInput::-webkit-scrollbar {
display: none; /*Chrome ??, webkit based*/
}
/*OLD CODE:*/
.CETextInput:not(.empty) br,
.CETextInput img { /*We hide <img> here. If you need images do not hide them but set maximum height. User can paste image by pressing Ctrl+V or Ctrl+Insert.*/
display: none;
}
.CETextInput * {
display: inline;
white-space: pre;
}
<!--NEW CODE:-->
<div class="CETextInput" contenteditable></div>
This solution has 3 problems with paddings:
In Firefox (tested on 2019-05-11, Firefox 66) there is no right padding when long text is typed. That is because Firefox does not display bottom or right padding when using padding in the same element that have scrollbar and when content is scrolled to the end.
In all browsers there is no padding when scrolling long text in middle position. It looks worse. <input type="text"> does not have this problem.
When user press home or end browsers scroll to place paddings are not visible.
To solve these problems you need use 3 elements like we used before but in this case you don't need use scrollbar-width. Our solution with 3 elements does not have these problems.
Other problems (in every solution):
Blur on pasting text ends with line break. I will think how to fix it.
When using paddings this.children[0].focus() is not enough in webkit-based browsers (cursor position is not where user clicked). I will think how to fix it.
Firefox (tested on 2019-05-11, Firefox 66): When short text is typed user cannot select last word by double clicking on the right of it. I will think about it.
When user starts text selection in the page he can end it in our field. Usual <input type="text"> does not have this behavior. But I don't think it is critical.
I think you are looking for a contenteditable div with only one line of text that scrolls horizontally when it overflows the div. This should do the trick: http://jsfiddle.net/F6C9T/1
div {
font-family: Arial;
font-size: 18px;
min-height: 40px;
width: 300px;
border: 1px solid red;
overflow: hidden;
white-space: nowrap;
}
<div contenteditable>
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
</div>
The min-height: 40px incorporates the height for when the horizontal scroll bar appears. A min-height:20px would automatically expand when the horizontal scroll bar appears, but this doesn't work in IE7 (though you could use conditional comments to apply separate styling if you wanted it).
I adapted the #tw16 accepted solution (on 5th Dec 2019) to add in scrolling. The trick was to add scrolling using overflow-x: auto but then hide the scrollbar (https://stackoverflow.com/a/49278385)
/* Existing Solution */
[contenteditable="true"].single-line {
white-space: nowrap;
width: 200px;
overflow: hidden;
}
[contenteditable="true"].single-line br {
display:none;
}
[contenteditable="true"].single-line * {
display:inline;
white-space:nowrap;
}
/* Make Scrollable */
[contenteditable="true"].single-line {
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* Internet Explorer 10+ */
}
[contenteditable="true"].single-line::-webkit-scrollbar { /* WebKit */
width: 0;
height: 0;
}
<div contenteditable="true" class="single-line">
This should scroll when you have really long text!
</div>
Here's a relatively simple solution that uses the contenteditable's input event to scan the dom and filter out various flavors of new lines (so it should be robust against copy/paste, drag 'n drop, hitting enter on the keyboard, etc). It condenses multiple TextNodes into single TextNodes, strips newlines from TextNodes, kills BRs, and puts a "display: inline" on any other element that it touches. Tested on Chrome, no guarantees anywhere else.
var editable = $('#editable')
editable.on('input', function() {
return filter_newlines(editable);
});
function filter_newlines(div) {
var node, prev, _i, _len, _ref, _results;
prev = null;
_ref = div.contents();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
if (node.nodeType === 3) {
node.nodeValue = node.nodeValue.replace('\n', '');
if (prev) {
node.nodeValue = prev.nodeValue + node.nodeValue;
$(prev).remove();
}
_results.push(prev = node);
} else if (node.tagName.toLowerCase() === 'br') {
_results.push($(node).remove());
} else {
$(node).css('display', 'inline');
filter_newlines($(node));
_results.push(prev = null);
}
}
return _results;
}
#editable {
width: 200px;
height: 20px;
border: 1px solid black;
}
<div id="editable" contenteditable="true"></div>
Or here's the fiddle: http://jsfiddle.net/tG9Qa/
If you want a different way of solving it other than changing the requirements, with a little display:table it is fully possible =)
.container1 {
height:20px;
width:273px;
overflow:hidden;
border:1px solid green;
}
.container2 {
display:table;
}
.textarea {
width:273px;
font-size: 18px;
font-weight: normal;
line-height: 18px;
outline: none;
display: table-cell;
position: relative;
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
word-wrap: break-word;
overflow:hidden;
}
<div class="container1">
<div class="container2">
<div contenteditable="true" class="textarea"></div>
</div>
</div>
So, for posterity: the simplest solution is to get your product manager to change the requirements so you can do multiline editing. This is what ended up happening in our case.
However, before that happened, I ended up going quite a way in creating a manually moving single-line richtext editor. I wrapped it up in a jQuery plugin in the end. I don't have time to finish it up (there are probably bugs in IE, Firefox works best and Chrome works pretty well - comments are sparse and sometimes not very clear). It uses parts of the Rangy library (extracted because I didn't want to rely on the complete library) to get screen positions of selections in order to test for mouse position vs. selection (so you can drag selections and move the box).
Roughly, it works by using 3 elements. An outer div (the thing you call the plugin on), which gets overflow: hidden, and then 2 levels of nesting inside it. The first level is absolutely positioned, the second level is the actual contenteditable. This separation is necessary because otherwise some browsers will give the contenteditable absolutely positioned element grippies, to let the user move it around...
In any case, then there is a whole bunch of code to move the absolutely positioned element around inside the top element, thus moving the actual contenteditable. The contenteditable itself has white-space nowrap, etc. etc. to force it to stay a single line.
There is also code in the plugin that strips out anything that isn't an image (like br, tables, etc. etc.) from any text that's pasted / dragged into the box. You need some parts of this (like the brs, stripping/normalizing paragraphs, etc.) but maybe you would normally want to keep links, em, strong and/or some other formatting.
Source: https://gist.github.com/1161922
Check out this answer I just posted. This should help you out:
How to create a HTML5 single line contentEditable tab which listens to Enter and Esc
Here is the HTML markup:
<span contenteditable="false"></span>
Here is the jQuery/javascript:
$(document).ready(function() {
$('[contenteditable]').dblclick(function() {
$(this).attr('contenteditable', 'true');
clearSelection();
$(this).trigger('focus');
});
$('[contenteditable]').live('focus', function() {
before = $(this).text();
if($(this).attr('contenteditable') == "true") { $(this).css('border', '1px solid #ffd646'); }
//}).live('paste', function() {
}).live('blur', function() {
$(this).attr('contenteditable', 'false');
$(this).css('border', '1px solid #fafafa');
$(this).text($(this).text().replace(/(\r\n|\n|\r)/gm,""));
if (before != $(this).text()) { $(this).trigger('change'); }
}).live('keyup', function(event) {
// ESC=27, Enter=13
if (event.which == 27) {
$(this).text(before);
$(this).trigger('blur');
} else if (event.which == 13) {
$(this).trigger('blur');
}
});
$('[contenteditable]').live('change', function() {
var $thisText = $(this).text();
//Do something with the new value.
});
});
function clearSelection() {
if ( document.selection ) {
document.selection.empty();
} else if ( window.getSelection ) {
window.getSelection().removeAllRanges();
}
}
Hope this helps someone!!!
You can replace this div with text input (after onclick event is called).
I have used something similar to this plugin and it worked fine.
with jQuery I have set a .keypress event and then tests for e.keyCode == 13 (return key) and if is return false from the event and the editing is not able to make multilines
$('*[contenteditable=yes]').keypress(function(e) {
if(e.keyCode == 13 && !$(this).data('multiline')) {
return false;
}
})