Search code examples
cssoutline

CSS outline is appearing on unexpected places


This may be a dumb question, but this thing is bothering me more than it should. It's a known fact that Google Chrome outlines <input> elements by default when they're focused. I don't like its default appearance so I implemented my own outline for the focus selector on my CSS:

#LoginForm input:focus {
    outline: #1F377A dotted 1px;
}

The original Chrome's implementation looks as follows (notice the blue outline around the text input):

Chrome's outline on focus

But by using my own css implementation it looks like this:

My outline

Why does my outline appears inside the text input and not around as chrome's default outline does?

These are the relevant css lines for my input element:

#LoginForm input {
    display: blocK;
    float: left;
    height: 24px;
    border: none;
    font-family: inherit;
    margin: 0px 0px 0px 4px;
}

#LoginForm input:focus {
    outline: red solid 1px;
}

#LoginForm .textInput {
    padding: 0px 2px 0px 2px;
    font-size: 9pt;
}

The only thing that let's me change between my own and chrome's outline is just commenting the input:focus selector and nothing more. I don't want to use borders, since the actually add to the size of the element and I don't want that.


Solution

  • If you check the chrome dev tools, the outline is not a simple 1px outline but shows up as

    :focus {
        outline-color: -webkit-focus-ring-color;
        outline-style: auto;
        outline-width: 5px;
    }
    
    input:focus, textarea:focus, keygen:focus, select:focus {
        outline-offset: -2px;
    }
    

    The outline-offset is what you where looking for. To have a red outline simply add this to your style sheet:

    :focus {
         outline-color: #f00;
    }
    

    If you also want it on other elements use:

    .element:focus {
        outline-color: #f00;
        outline-style: auto;
        outline-width: 5px;
        outline-offset: -2px;
    }
    

    Here's a JSFiddle to play with.


    EDIT:

    To have the outline exactly on the border (and not inside of it) you have to set

    outline-offset: 0;
    

    to override the chrome user agent styles.