I have the following code, I am trying to understand why all the elements are not layed out on the same line. It’s because I added padding, but shouldn’t the padding be accounted for when laying out the elements? I checked on IE, Firefox, and Chrome. They all lay out the last element on the next line.
Can someone explain why, and how do I get all the elements on the same line and keep the padding I put on them?
Thanks
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.body{PADDING:0PX;MARGIN:0PX}
.bar{WIDTH:100%;HEIGHT:20PX;BACKGROUND-COLOR:#FFFFFF;}
.item{WIDTH:25%;HEIGHT:20PX;DISPLAY:INLINE-BLOCK;COLOR:#000000;PADDING:5PX;}
</style>
</head>
<body class="body">
<div id="menubar" class="bar">
<div class="item">B1</div>
<div class="item">B2</div>
<div class="item">B3</div>
<div class="item">B4</div>
</div>
</body>
</html>
B4 display on a new line.
The output I want is:
B1 B2 B3 B4
The output I get is:
B1 B2 B3
B4
With
inline-blocklayouts, the elements are affected by whitespace and vertical layout, in addition to any padding you add. When working with this form of layout, it’s best to always usevertical-align: top;. This gives you a consistent starting point to work from.The whitespace problem with
inline-blockis that any spaces between elements in your HTML get treated just like they would with text in HTML and get condensed into a single space. So, in addition to any padding or margins you’ve set, you have this space to deal with. To get rid of it you can bunch your elements together, or comment out the whitespace.So in your case, in addition to the 25%, it’s adding whitespace and padding. The easiest fix is to change your padding to top and bottom only. Since your design is a flex layout, your left and right padding is taken care of another way: by the stretchiness of it. If there is an issue with the text being butted up against a border on the left, you can use
text-indent: 5px;as a replacement forpadding-left: 5px;. It doesn’t affect layout.Demo: http://jsfiddle.net/ThinkingStiff/xAEhY/
Change:
To:
Here’s a demo that illustrates the issues with
inline-blocklayouts and how to deal with them.Demo: http://jsfiddle.net/ThinkingStiff/axjba/
HTML:
CSS:
Output: