Best way to compare dates in Android

Question I am trying to compare a date in a String format to the current date. This is how I did it (haven’t tested, but should work), but am using deprecated methods. Any good suggestion for an alternative? Thanks. P.S. I really hate doing Date stuff in Java. There are so many ways to do… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Android – Activity Constructor vs onCreate

Question I understand that Android Activities have specific lifecycles and that onCreate should be overridden and used for initialization, but what exactly happens in the constructor? Are there any cases when you could/should override the Activity constructor as well, or should you never touch it? I’m assuming that the constructor should never be used because… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Can two Java methods have same name with different return types?

Question Can two Java methods have the same name with different return type? The return type of the methods are different and they are declared with the same method’s name. Is that allowed? Solution If both methods have same parameter types, but different return type than it is not possible. From Java Language Specification, Java… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to modify JsonNode in Java?

Question I need to change a JSON attribute’s value in Java, I can get the value properly but I couldn’t modify the JSON. here is the code below JsonNode blablas = mapper.readTree(parser).get(“blablas”); for (JsonNode jsonNode : blablas) { String elementId = jsonNode.get(“element”).asText(); String value = jsonNode.get(“value”).asText(); if (StringUtils.equalsIgnoreCase(elementId, “blabla”)) { if(value != null && value.equals(“YES”)){… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What is the difference between cascade and orphan removal from DB?

Question What’s the difference between @OneToMany(cascade=REMOVE, mappedBy=”customer”) public List<Order> getOrders() { … } and @OneToMany(mappedBy=”customer”, orphanRemoval=”true”) public List<Order> getOrders() { … } This example is from Java EE Tutorial, but I still don’t understand details. Solution From here:- Cascading Remove Marking a reference field with CascadeType.REMOVE (or CascadeType.ALL, which includes REMOVE) indicates that remove operations… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Get battery level and state in Android

Question How can I get battery level and state (plugged in, discharging, charging, etc)? I researched the developer docs and I found a BatteryManager class. But it doesn’t contain any methods, just constants. How do I even use it? Solution Here is a code sample that explains how to get battery information. To sum it… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Where is logback encoder pattern documentation

Question I’ve gone through all the documentation of logback and I can’t find anywhere the documentation to configure the encoder’s pattern when logging, such as: <encoder> <pattern>%d{HH:mm:ss.SSS} %-4relative %-5level %logger{35} – %msg%n</pattern> </encoder> I would like a table (like the one that log4j has) explaining the different options to configure the pattern. Where is the… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Performance of ThreadLocal variable

Question How much is read from ThreadLocal variable slower than from regular field? More concretely is simple object creation faster or slower than access to ThreadLocal variable? I assume that it is fast enough so that having ThreadLocal<MessageDigest> instance is much faster then creating instance of MessageDigest every time. But does that also apply for… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java Mouse Event Right Click

Question On my three button mouse MouseEvent.BUTTON2= Middle Click and MouseEvent.BUTTON3 = Right Click. Is this the case on a two button mouse? Thanks Solution To avoid any ambiguity, use the utilities methods from SwingUtilities : SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent) barjakbarjak

Share this article:
Follow us on Twitter Follow us on Facebook

How can I download all emails with attachments from Gmail?

Question How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it. Solution Hard one 🙂 import email, getpass, imaplib, os detach_dir = ‘.’ # directory where to save attachments (default: current) user =… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Change position of Google Maps API’s “My location” button

Question I am using the Google Maps Android API v2, and I need a way to chance the position of the “My Location” button. I get the “My Location” button like this: GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); final GoogleMap map = ((SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map)).getMap(); // This gets the button map.setMyLocationEnabled(true); Solution Just use GoogleMap.setPadding(left, top, right, bottom), which allows… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do you deal with maven-3 timestamped snapshots efficiently?

Question Now that maven-3 did drop support for the <uniqueVersion>false</uniqueVersion> for snapshot artefacts it seems that you really need to use timestamped SNAPSHOTS. Especially m2eclipse, which does use maven 3 internally seems to be affected with it, update-snapshots does not work when the SNAPSHOTS are not unique. It seemed best practice before to set all… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What’s the difference between failure and error in JUnit?

Question I’m running JUnit tests on a large code base, and I’ve been realizing that sometimes I get “Errors” while other times I get “Failures”. What’s the difference? Solution Ok, I’ve just noticed a pattern and think I’ve figured it out (correct me if I’m wrong). It seems to me that failures are when your… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

IntelliJ IDEA 12 code completion without capitalisation

Question In eclipse 4.2, I can just type: joptionpane and press CTRL+SPACE and it will turn into: JOptionPane Is there any way to do the same with intelliJ IDEA? I have tried pressing CTRL+SPACE, and ALT+/. But, for some reason it just does not work. I would be most grateful if anyone could show me… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Can I multiply strings in Java to repeat sequences?

Question I have something like the following: int i = 3; String someNum = “123”; I’d like to append i “0”s to the someNum string. Does it have some way I can multiply a string to repeat it like Python does? So I could just go: someNum = sumNum + (“0” * 3); or something… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

HttpSecurity, WebSecurity and AuthenticationManagerBuilder

Question Could anyone explain when to override configure(HttpSecurity), configure(WebSecurity) and configure(AuthenticationManagerBuilder)? Solution configure(AuthenticationManagerBuilder) is used to establish an authentication mechanism by allowing AuthenticationProviders to be added easily: e.g. The following defines the in-memory authentication with the in-built ‘user’ and ‘admin’ logins. public void configure(AuthenticationManagerBuilder auth) { auth .inMemoryAuthentication() .withUser(“user”) .password(“password”) .roles(“USER”) .and() .withUser(“admin”) .password(“password”) .roles(“ADMIN”,”USER”);… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to use cURL in Java?

Question I am a newbie in java and wanted to use curl in java. What is my question is curl built-in in java or I have to install it from any 3rd party source to use with Java. If so, how to install curl in java. I have been googling for a long time but… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Inheritance and recursion

Question Suppose we have the following classes: class A { void recursive(int i) { System.out.println(“A.recursive(” + i + “)”); if (i > 0) { recursive(i – 1); } } } class B extends A { void recursive(int i) { System.out.println(“B.recursive(” + i + “)”); super.recursive(i + 1); } } Now lets call recursive in class… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to check a string against null in java?

Question How can I check a string against null in java? I am using stringname.equalsignorecase(null) but it’s not working. Solution string == null compares if the object is null. string.equals(“foo”) compares the value inside of that object. string == “foo” doesn’t always work, because you’re trying to see if the objects are the same, not… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What’s the difference between a Resource, URI, URL, Path and File in Java?

Question I’m looking at a piece of Java code right now, and it takes a path as a String and gets its URL using URL resource = ClassLoader.getSystemClassLoader().getResource(pathAsString);, then calls String path = resource.getPath() and finally executes new File(path);. Oh, and there are also calls to URL url = resource.toURI(); and String file = resource.getFile().… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do I set the timeout for a JAX-WS webservice client?

Question I’ve used JAXWS-RI 2.1 to create an interface for my web service, based on a WSDL. I can interact with the web service no problems, but haven’t been able to specify a timeout for sending requests to the web service. If for some reason it does not respond the client just seems to spin… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What is the difference between List.of and Arrays.asList?

Question Java 9 introduced a new factory methods for lists, List.of: List<String> strings = List.of(“first”, “second”); What’s the difference between the previous and the new option? That is, what’s the difference between this: Arrays.asList(1, 2, 3); and this: List.of(1, 2, 3); Solution Arrays.asList returns a mutable list while the list returned by List.of is immutable:… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Converting byte array to String (Java)

Question I’m writing a web application in Google app Engine. It allows people to basically edit html code that gets stored as an .html file in the blobstore. I’m using fetchData to return a byte[] of all the characters in the file. I’m trying to print to an html in order for the user to… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java logical operator short-circuiting

Question Which set is short-circuiting, and what exactly does it mean that the complex conditional expression is short-circuiting? public static void main(String[] args) { int x, y, z; x = 10; y = 20; z = 30; // T T // T F // F T // F F //SET A boolean a = (x… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Large difference in speed of equivalent static and non static methods

Question In this code when I create an Object in the main method and then call that objects method: ff.twentyDivCount(i)(runs in 16010 ms) , it runs much faster than calling it using this annotation: twentyDivCount(i)(runs in 59516 ms). Of course, when I run it without creating an object, I make the method static, so it… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to solve javax.net.ssl.SSLHandshakeException Error?

Question I connected with VPN to setup the inventory API to get product list and it works fine. Once I get the result from the web-service and i bind to UI. And also I integrated PayPal with my application for make Express checkout when I make a call for payment I’m facing this error. I… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Explode and Implode (just like PHP) in Java

Question I am new in Java although had a good experience in PHP, and looking for perfect replacement for explode and implode (available in PHP) functions in Java. I have Googled for the same but not satisfied with the results. Anyone has the good solution for my problem will be appreciated. For example: String s… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to see if an object is an array without using reflection?

Question How can I see in Java if an Object is an array without using reflection? And how can I iterate through all items without using reflection? I use Google GWT so I am not allowed to use reflection 🙁 I would love to implement the following methods without using refelection: private boolean isArray(final Object… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to import a class from default package

Question Possible Duplicate: How to access java-classes in the default-package? I am using Eclipse 3.5 and I have created a project with some package structure along with the default package. I have one class in default package – Calculations.java and I want to make the use of that class in any of the package (for… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Increase permgen space

Question I am working with tomcat 6.0, and while I am indexing (not while i am starting tomcat), I have a permgen space error. How could I increase that space?? Thanks Solution You can use : -XX:MaxPermSize=128m to increase the space. But this usually only postpones the inevitable. You can also enable the PermGen to… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Array Length in Java

Question I declared an array as shown below: int[] arr = new int[10]; Then I assigned following values to the array: arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; Then I declared and initialized an integer variable: int arrayLength = arr.length; This will be useful to find actual size but is… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What is the maximum depth of the java call stack?

Question How deep do I need to go into the call stack before I get a StackOverflowError? Is the answer platform dependent? Solution It depends on the amount of virtual memory allocated to the stack. http://www.odi.ch/weblog/posting.php?posting=411 You can tune this with the -Xss VM parameter or with the Thread(ThreadGroup, Runnable, String, long) constructor. finnwfinnw

Share this article:
Follow us on Twitter Follow us on Facebook

Is it better to return an ImmutableMap or a Map?

Question Let’s say I’m writing a method that should return a Map. For instance: public Map<String, Integer> foo() { return new HashMap<String, Integer>(); } After thinking about it for a while, I’ve decided that there is no reason to modify this Map once it is created. Thus, I would like to return an ImmutableMap. public… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Should I strictly avoid using enums on Android?

Question I used to define a set of related constants like Bundle keys together in an interface like below: public interface From{ String LOGIN_SCREEN = “LoginSCreen”; String NOTIFICATION = “Notification”; String WIDGET = “widget”; } This provides me a nicer way to group related constants together and used them by making a static import (not… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Does java.util.List.isEmpty() check if the list itself is null?

Question Does java.util.List.isEmpty() check if the list itself is null, or do I have to do this check myself? For example: List<String> test = null; if (!test.isEmpty()) { for (String o : test) { // do stuff here } } Will this throw a NullPointerException because test is null? Solution You’re trying to call the… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How can I compile a Java program in Eclipse without running it?

Question I would like to compile my Java program in Eclipse but not to run it. I can’t understand how to do it. How can I compile a Java program to .class files in Eclipse without running it? Solution You can un-check the build automatically in Project menu and then build by hand by type… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Android: Dex cannot parse version 52 byte code

Question I just switched to Android Studio 2.1 and this error showed up when trying to compile an app the was previously working: Error:Error converting bytecode to dex: Cause: Dex cannot parse version 52 byte code. This is caused by library dependencies that have been compiled using Java 8 or above. If you are using… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java dynamic array sizes?

Question I have a class – xClass, that I want to load into an array of xClass so I the declaration: xClass mysclass[] = new xClass[10]; myclass[0] = new xClass(); myclass[9] = new xClass(); However, I don’t know if I will need 10. I may need 8 or 12 or any other number for that… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java: Equivalent of Python’s range(int, int)?

Question Does Java have an equivalent to Python’s range(int, int) method? Solution Guava also provides something similar to Python’s range: Range.closed(1, 5).asSet(DiscreteDomains.integers()); You can also implement a fairly simple iterator to do the same sort of thing using Guava’s AbstractIterator: return new AbstractIterator<Integer>() { int next = getStart(); @Override protected Integer computeNext() { if (isBeyondEnd(next))… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Creating a custom JButton in Java

Question Is there a way to create a JButton with your own button graphic and not just with an image inside the button? If not, is there another way to create a custom JButton in java? Solution When I was first learning Java we had to make Yahtzee and I thought it would be cool… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

HQL ERROR: Path expected for join

Question I keep trying variations of this query and can’t seem to make this happen. I’ve also referenced this post: Path Expected for Join! Nhibernate Error and can’t seem to apply the same logic to my query. My User object has a UserGroup collection. I understand that the query needs to reference entities within the… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Eclipse – debugger doesn’t stop at breakpoint

Question I am trying to trouble shoot a JUnit. In the source code, I have set break point in two places: 1) in a line where a static member is initialized 2) the first line of one of the test cases. The debugger stops in the static field initializing line. But it doesn’t stop in… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Java Timestamp – How can I create a Timestamp with the date 23/09/2007?

Question How can I create a Timestamp with the date 23/09/2007? Solution By Timestamp, I presume you mean java.sql.Timestamp. You will notice that this class has a constructor that accepts a long argument. You can parse this using the DateFormat class: DateFormat dateFormat = new SimpleDateFormat(“dd/MM/yyyy”); Date date = dateFormat.parse(“23/09/2007”); long time = date.getTime(); new… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

When is an interface with a default method initialized?

Question While searching through the Java Language Specification to answer this question, I learned that Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class are not initialized. Similarly, the superinterfaces of an interface are not initialized before the interface is initialized. For my own curiosity, I tried… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Is it possible to view bytecode of Class file?

Question Possible Duplicate:Is there a java classfile / bytecode editor to edit instructions? Java source code is compiled into bytecode, which is actually in the class file. Is it possible to view bytecode of a compiled class? If it is possible, can it be edited? Is there an eclipse plugin for that available? Solution Yes.… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

spring scoped proxy bean

Question Can someone explain the usage of the spring @ScopedProxy annotation? I thought it had something to do with session scoped beans, but I’m not quite sure what. In my usage of scopes, I’ve used session scoped beans without the @ScopedProxy annotation (or without aop scoped proxies), so I’m really sure how to use it… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to analyze a java thread dump?

Question I am trying to understand more about java, especially about memory management and threads. For this reason I have recently found interest in looking at thread dumps. Here are few lines taken from a web app using VisualVM, a built-in tool for java: “Finalizer” daemon prio=8 tid=0x02b3d000 nid=0x898 in Object.wait() [0x02d0f000] java.lang.Thread.State: WAITING (on… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Distributed sequence number generation?

Question I’ve generally implemented sequence number generation using database sequences in the past. e.g. Using Postgres SERIAL type http://www.neilconway.org/docs/sequences/ I’m curious though as how to generate sequence numbers for large distributed systems where there is no database. Does anybody have any experience or suggestions of a best practice for achieving sequence number generation in a… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Spring get current ApplicationContext

Question I am using Spring MVC for my web application. My beans are written in “spring-servlet.xml” file Now I have a class MyClass and i want to access this class using spring bean In the spring-servlet.xml i have written following <bean id=”myClass” class=”com.lynas.MyClass” /> Now i need to access this using ApplicationContext ApplicationContext context =… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Is the creation of Java class files deterministic?

Question When using the same JDK (i.e. the same javac executable), are the generated class files always identical? Can there be a difference depending on the operating system or hardware? Except of the JDK version, could there be any other factors resulting in differences? Are there any compiler options to avoid differences? Is a difference… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Difference between C# and Java’s ternary operator (? :)

Question I am a C# newbie and I just encounter a problem. There is a difference between C# and Java when dealing with the ternary operator (? :). In the following code segment, why does the 4th line not work? The compiler shows an error message of there is no implicit conversion between ‘int’ and… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do you add CSS with Javascript?

Question How do you add CSS rules (eg strong { color: red }) by use of Javascript? Solution You can also do this using DOM Level 2 CSS interfaces (MDN): var sheet = window.document.styleSheets[0]; sheet.insertRule(‘strong { color: red; }’, sheet.cssRules.length); …on all but (naturally) IE, which uses its own marginally-different wording: sheet.addRule(‘strong’, ‘color: red;’, -1);… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to make Twitter bootstrap modal full screen

Question <div id=”myModal” class=”modal hide fade” tabindex=”-1″ role=”dialog” aria-labelledby=”myModalLabel” aria-hidden=”true”> <div class=”modal-body”> <%= image_tag “Background.jpg” %> </div> </div> How do I make a twitter bootstrap modal popup full screen for the above code, I tried playing around with css but was not able get it the way I wanted. Can anyone please help me with… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

IE7 does not understand display: inline-block

Question Can someone please help me get my head around this bug? With Firefox its working fine but with Internet Explorer 7 its not. It seems not to understand the display: inline-block;. html: <div class=”frame-header”> <h2>…</h2> </div> css: .frame-header { height:25px; display:inline-block; } Solution The IE7 display: inline-block; hack is as follows: display: inline-block; *display:… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

SPAN vs DIV (inline-block)

Question Is there any reason to use a <div style=”display:inline-block”> instead of a <span> to layout a webpage? Can I put content nested inside the span? What is valid and what isn’t? It’s ok to use this to make a 3×2 table like layout? <div> <span> content1(divs,p, spans, etc) </span> <span> content2(divs,p, spans, etc) </span>… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

CSS last-child selector: select last-element of specific class, not last child inside of parent?

Question <div class=”commentList”> <article class=”comment ” id=”com21″></article> <article class=”comment ” id=”com20″></article> <article class=”comment ” id=”com19″></article> <div class=”something”> hello </div> </div> I want to select #com19 ? .comment { width:470px; border-bottom:1px dotted #f0f0f0; margin-bottom:10px; } .comment:last-child { border-bottom:none; margin-bottom:0; } That does not work as long as I do have another div.something as actual last child… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How can I show dots (“…”) in a span with hidden overflow?

Question My CSS: #content_right_head span { display:inline-block; width:180px; overflow:hidden !important; } Now it’s showing content content But I want to show like content content … I need to show dots after contents. Contents are coming dynamically from database. Solution For this you can use text-overflow: ellipsis; property. Write like this span { display: inline-block; width:… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

IE 8: background-size fix

Question I’ve tried to add background size to IE but it’s not working at all: HTML <h2 id=”news”>Notícias <img src=”white-marker.png” alt=”” /></h2> CSS: div#content h2#news { background: url(‘../images/news-background.jpg’) no-repeat; background-size: 100%; border-radius: 20px; color: #fff; margin: 20px 0 0 20px; padding: 8px 20px; width: 90%; -moz-background-size: 100%; -moz-border-radius: 20px; -webkit-background-size: 100%; -webkit-border-radius: 20px; } What’s… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Fixed width buttons with Bootstrap

Question Does Bootstrap support fixed width buttons? Currently if I have 2 buttons, “Save” and “Download”, the button size changes based on content. Also what is the right way of extending Bootstrap? Solution You can also use the .btn-block class on the button, so that it expands to the parent’s width. If the parent is… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Losing style of a within within a flash object?

Question Here is the story: I’m using SWFObject to insert a Flash object into my page. The embedding eats my span. So, I lose all my CSS for it. I was thinking of moving all of the CSS to the parent so I don’t lose my CSS styles when the Flash appears. I have tried… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Modify alpha opacity of LESS variable

Question Using LESS, I know that I can change the saturation or tint of a color variable. That looks like this: background: lighten(@blue, 20%); I want to change the alpha opacity of my color, though. Preferably like this: background: alpha(@blue, 20%); Is there a simple way to do this in LESS? Solution The site documentation… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

CSS checkbox input styling

Question Any style for input affects every input element. Is there a way to specify styling to apply for only checkboxes without applying a class to each check box element? Solution With CSS 2 you can do this: input[type=’checkbox’] { … } This should be pretty widely support by now.. To see support for browsers,… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

“Eliminate render-blocking CSS in above-the-fold content”

Question I’ve been using Google PageSpeed insights to try and improve my site’s performance, and so far it’s proven extremely successful. Things like deferring scripts worked beautifully, since I already had an in-house version of jQuery’s .ready() to defer scripts until the page had loaded fully, all I had to do was inline that particular… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Inspect webkit-input-placeholder with developer tools

Question It’s possible to style a text input’s placeholder with the following: -webkit-input-placeholder { color: red; } I am looking at a website online and I would like to use the same placeholder color as they do. Is it possible to figure out what color they used? I would like to include any alpha values,… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to write a CSS hack for IE 11?

Question How can I hack or write css only for IE 11? I have a website that looks bad in IE 11.I just search here and there but didnt find any solution yet. Is there any css selector? Solution Use a combination of Microsoft specific CSS rules to filter IE11: <!doctype html> <html> <head> <title>IE10/11… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

CSS Printing: Avoiding cut-in-half DIVs between pages?

Question I’m writing a plug-in for a piece of software that takes a big collection of items and pops them into HTML in a WebView in Cocoa (which uses WebKit as its renderer, so basically you can assume this HTML file is being opened in Safari). The DIVs it makes are of dynamic height, but… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Style input element to fill remaining width of its container

Question Let’s say I have an html snippet like this: <div style=”width:300px;”> <label for=”MyInput”>label text</label> <input type=”text” id=”MyInput” /> </div> This isn’t my exact code, but the important thing is there’s a label and a text input on the same line in a fixed-width container. How can I style the input to fill the remaining… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Changing the width of Bootstrap popover

Question I am designing a page using Bootstrap 3. I am trying to use a popover with placement: right on an input element. The new Bootstrap ensures that if you use form-control you basically have a full-width input element. The HTML code looks something like this: <div class=”row”> <div class=”col-md-6″> <label for=”name”>Name:</label> <input id=”name” class=”form-control”… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Place a button right aligned

Question I use this code to right align a button. <p align=”right”> <input type=”button” value=”Click Me” /> </p> But P tags wastes some space, so looking to do the same with span or div. Solution Which alignment technique you use depends on your circumstances but the basic one is float: right;: <input type=”button” value=”Click Me”… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Using CSS to insert text

Question I’m relatively new to CSS, and have used it to change the style and formatting of text. I would now like to use it to insert text as shown below: <span class=”OwnerJoe”>reconcile all entries</span> Which I hope I could get to show as: Joe’s Task: reconcile all entries That is, simply by virtue of… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

CSS How to set div height 100% minus nPx

Question I have a wrapper div which contans 2 divs next to each other. Above this container I have a div that contains my header. The wrapper div must be 100% minus the height of the header. The header is about 60 px. This is fixed. So my question is: how do I set the… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do I auto-hide placeholder text upon focus using css or jquery?

Question This is done automatically for every browser except Chrome. I’m guessing I have to specifically target Chrome. Any solutions? If not with CSS, then with jQuery? Solution <input type=”text” placeholder=”enter your text” onfocus=”this.placeholder = ”” onblur=”this.placeholder = ‘enter your text'” /> MatuDukeMatuDuke

Share this article:
Follow us on Twitter Follow us on Facebook

How to change the style of the title attribute inside an anchor tag?

Question Example: <a href=”example.com” title=”My site”> Link </a> How do I change the “title” attribute. By default, it just has yellow background and small font. I would like to make it bigger and change the background color. Is there a CSS way to style the title attribute? Solution Here is an example of how to… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Convert RGB to RGBA over white

Question I have a hex color, e.g. #F4F8FB (or rgb(244, 248, 251)) that I want converted into an as-transparent-as-possible rgba color (when displayed over white). Make sense? I’m looking for an algorithm, or at least idea of an algorithm for how to do so. For Example: rgb( 128, 128, 255 ) –> rgba( 0, 0,… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to set the margin or padding as percentage of height of parent container?

Question I had been racking my brains over creating a vertical alignment in css using the following .base{ background-color:green; width:200px; height:200px; overflow:auto; position:relative; } .vert-align{ padding-top:50%; height:50%; } and used the following div structure. <div class=”base”> <div class=”vert-align”> Content Here </div> </div> While this seemed to work for this case, i was surprised that when… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Which font for CSS “x” close button?

Question I want to create a close button using CSS only. I’m sure I’m not the first to do this, so does anyone know which font has an ‘x’ the same width as height, so that it can be used cross-browser to look like a close button? Solution ✖ works really well. The HTML code… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Are the decimal places in a CSS width respected?

Question Something I’ve been wondering for a while whilst doing CSS design. Are decimal places in css widths respected? Or are they rounded? .percentage { width: 49.5%; } or .pixel { width: 122.5px; } Solution If it’s a percentage width, then yes, it is respected. As Martin pointed out, things break down when you get… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Truncating long strings with CSS: feasible yet?

Question Is there any good way of truncating text with plain HTML and CSS, so that dynamic content can fit in a fixed-width-and-height layout? I’ve been truncating server-side by logical width (i.e. a blindly-guessed number of characters), but since a ‘w’ is wider than an ‘i’ this tends to be suboptimal, and also requires me… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to generate a simple popup using jQuery

Question I am designing a web page. When we click the content of div named mail, how can I show a popup window containing a label email and text box? Solution First the CSS – tweak this however you like: a.selected { background-color:#1F75CC; color:white; z-index:100; } .messagepop { background-color:#FFFFFF; border:1px solid #999999; cursor:default; display:none; margin-top:… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Transitions on the display: property

Question I’m currently designing a kind of CSS ‘mega dropdown’ menu – basically a normal CSS-only dropdown menu, but one that contains different types of content. At the moment, it appears that CSS3 Transitions don’t apply to the ‘display’ property, i.e. you can’t do any sort of transition from display: none to display: block (or… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do I auto-resize an image to fit a div container

Question How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining it’s width:height ratio? Example: stackoverflow.com – when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized. Solution Do not… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to vertically center a div for all browsers?

Question I want to center a div vertically with CSS. I don’t want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support. <body> <div>Div to be aligned vertically</div> </body> How can I center a div vertically in all major browsers, including Internet Explorer… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to vertically align an image inside a div?

Question Question How can you align an image inside of a containing div? Example In my example, I need to vertically center the <img> in the <div> with class =”frame” : <div class=”frame” style=”height: 25px;”> <img src=”http://jsfiddle.net/img/logo.png” /> </div> .frame‘s height is fixed and image’s height is unknown. I can add new elements in .frame… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do I make a placeholder for a ‘select’ box?

Question I’m using placeholders for text inputs which is working out just fine. But I’d like to use a placeholder for my selectboxes as well. Ofcourse I can just use this code: <select> <option value=””>Select your option</option> <option value=”hurr”>Durr</option> </select> But the ‘Select your option’ is in black instead of lightgrey. So my solution could… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Click through div to underlying elements

Question I have a div that has background:transparent, along with border. Underneath this div, I have more elements. Currently, I’m able to click the underlying elements when I click outside of the overlay div. However, I’m unable to click the underlying elements when clicking directly on the overlay div. I want to be able to… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

What’s the difference between SCSS and Sass?

Question From what I’ve been reading, Sass is a language that makes CSS more powerful with variable and math support. What’s the difference with SCSS? Is it supposed to be the same language? Similar? Different? Solution Sass is a CSS pre-processor with syntax advancements. Style sheets in the advanced syntax are processed by the program,… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Make a div fill the height of the remaining screen space

Question I am currently working on a web application, where I want the content to fill the height of the entire screen. The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom.… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Convert HTML + CSS to PDF with PHP?

Question I have an HTML (not XHTML) document that renders fine in Firefox 3 and IE 7. It uses fairly basic CSS to style it and renders fine in HTML. I’m now after a way of converting it to PDF. I have tried: DOMPDF: it had huge problems with tables. I factored out my large… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How to align checkboxes and their labels consistently cross-browsers

Question This is one of the minor CSS problems that plagues me constantly. How do folks around Stack Overflow vertically align checkboxes and their labels consistently cross-browser? Whenever I align them correctly in Safari (usually using vertical-align: baseline on the input), they’re completely off in Firefox and IE. Fix it in Firefox, and Safari and… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

Make the cursor a hand when a user hovers over a list item

Question I’ve got a list, and I have a click handler for its items: <ul> <li>foo</li> <li>goo</li> </ul> How can I change the mouse pointer into a hand pointer (like when hovering over a button)? Right now the pointer turns into a text selection pointer when I hover over the list items. Solution In light… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook

How do CSS triangles work?

Question There’re plenty of different CSS shapes over at CSS Tricks – Shapes of CSS and I’m particularly puzzled with a triangle: #triangle-up { width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid transparent; border-bottom: 100px solid red; } <div id=”triangle-up”></div> How and why does it work? Solution CSS Triangles: A Tragedy in… Read More »

Share this article:
Follow us on Twitter Follow us on Facebook