Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS anchor inline-block misaligned

Tags:

html

css

I have this JSFiddle. Can someone explain, why is the anchor position misaligned relative to its siblings? I know I can correct it with position relative and negaitve top offset, but I don't understand, why it is like this in the first place.

HTML:

<div class="container">
    <div class="left"></div>
    <a href="">Some link</a>
    <div class="right"></div>
</div>

CSS:

.container {
    height: 25px;
    white-space: nowrap;
}

.container .left {
    border: 1px solid black;
    display: inline-block;
    margin: 0;
    height: 25px;
    width: 80px;
    padding: 0;
}

.container .right {
    border: 1px solid black;
    display: inline-block;
    margin: 0;
    height: 25px;
    width: 80px;
    padding: 0;
}

.container a {
    display: inline-block;
    border: 1px solid black;
    height: 25px;
    width: 300px;
    margin: 0;
}
like image 693
W.B. Avatar asked Dec 20 '22 18:12

W.B.


2 Answers

You can add

vertical-align: top;

to .container a

This wil align the anchor with the divs.

like image 20
Arno Avatar answered Jan 04 '23 20:01

Arno


The reason of this behaviour is due to the absence of text inside your .left and .right elements.

By default inline-block elements have vertical-align: baseline, but since you have empty elements there's no baseline, so they will be automatically aligned to the parent baseline (if you add some text inside them — even a &nbsp; — you would istantly solve the problem)

In order to prevent this behaviour you could also set a common vertical-align to all .container children.

like image 144
Fabrizio Calderan Avatar answered Jan 04 '23 18:01

Fabrizio Calderan