Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do 2 elements of 50% not fit in the same row

Tags:

css

Question

If both <li> are 50%, why won't they be side by side?

Code

Demo on jsfiddle.

HTML

<ul>
    <li>left</li>
    <li>right</li>
</ul>

CSS

ul {
    padding: 0;
}
li {
    list-style: none;
    display: inline-block;
    width: 50%;
    font-size: 12px;
    color: gray;
    background-color: rgb(216, 216, 216);
    padding: 3px;
    text-align: center;
    border: 1px solid rgba(179, 179, 179, 0.83);
}
like image 322
Nick Ginanto Avatar asked Jan 11 '23 16:01

Nick Ginanto


2 Answers

Because by default, margin padding and border are counted outside the element and not inside. So padding of 3px + border of 1px will be added to 50% on all the sides.

Also am not sure whether you are resetting browser default margin and padding of the elements, if you aren't than do it. You can either use universal selector which some oppose as it hits performance by few bits, like

* {
   margin: 0;
   padding: 0;
}

Or if you want to reset in a lenient way than you can use CSS Reset Stylesheet

enter image description here

So inorder to count the padding and border inside, you will have to use box-sizing property with a value of border-box.

Also you are using inline-block which will leave a margin / whitespace whatever you call of merely 4px so make all the li in one line. OR what you can do is, you can float your elements to the left, so that you don't have to make all the li in one line in your source document.

Demo


Just make sure you clear your floating elements if you are going with the float solution.

like image 57
Mr. Alien Avatar answered Jan 14 '23 04:01

Mr. Alien


First problem: With the display:inline-block property, there is a white-space betwen elements. This make the li elments 100% + white-space is more than 100% so they can't fit on same line better use float:left for your issue

Second problem: You give a 3px border which makes your li elements more than 50% wide you could use the property box-sizing:border-box; which would make your borders inside the li elements

CSS:

ul {
    padding: 0;
    padding:0;
}
li {
    list-style: none;
    float:left;
    width: 50%;
    font-size: 12px;
    color: gray;
    margin:0;
    padding:0;
    background-color: rgb(216, 216, 216);
    text-align: center;
    border: 1px solid rgba(179, 179, 179, 0.83);
    box-sizing:border-box;
}

JSFIDDLE

like image 35
web-tiki Avatar answered Jan 14 '23 05:01

web-tiki