0

Basically I have a div with this CSS:

.mydiv{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    padding:7px;   
}​

The browser shows the horizontal due to padding (width 100% + 7px)
Take a look here: http://jsfiddle.net/3FrLq/

How can I have that div not showing the horizontal bar? (Without having to add another div inside?)

6 Answers6

5

Get rid of the width:auto and replace it with right:0.

jsFiddle example

Since your element is positioned absolutely, you can in effect pull the left and right sides to the edges of the element's container without invoking the scrollbar.

j08691
  • 204,283
  • 31
  • 260
  • 272
2

Correct HTML semantics pretty much requires that you have another element inside. In this case, your text should be wrapped in <p> tags.

Doing that automatically gives you something to hook into to set margin or padding on the inner element.

That said, if you really can't/won't have an inner element, remove your width and set right: 0. The nifty thing about absolutely positioned elements is that if you set opposing positions to 0, you can "stretch" the element (it works with top/bottom, too).

Alternatively, if your element isn't positioned absolutely, you can change your width: 100% to max-width: 100% (or add the max-width line, to deal with a bug in an old version of IE, if you have to go back that far), which will hard-cap the total width. This one's in action here - http://jsfiddle.net/3FrLq/5/ .

Shauna
  • 9,495
  • 2
  • 37
  • 54
2

You can use the box-sizing: border-box CSS property which will exclude the padding and borders from the actual width and height of the element:

-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border -box;

Here's the fiddle: http://jsfiddle.net/3FrLq/3/

More info / browser support for box-sizing: https://developer.mozilla.org/en-US/docs/CSS/box-sizing

sbeliv01
  • 11,550
  • 2
  • 23
  • 24
  • That's nice... I really hate the box model. I hope one day browser will set width with the value of width really – dynamic Nov 13 '12 at 20:57
1

You can set the div to display inline-block:

.mydiv{
    display: inline-block;
    position:absolute;
    top:0;
    left:0;
    width:100%;
    padding:7px;   
}​

This will display it inline (not stretching horizontally), while allowing you to still apply padding and margins to the top and bottom (unlike display: inline

Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149
1

Get rid of width specifying & just specify 0px; for all 4 sides

tonino.j
  • 3,837
  • 28
  • 27
1
  • if IE8+ compatibility enough for you, you can use box-sizing.
  • if you want it to be working only with full width, set both left & right to 0, but do not set a width.
pozs
  • 34,608
  • 5
  • 57
  • 63