user9545614
user9545614

Reputation:

How to have a div as a box not span past/off the screen

I have the following block of code for the styling on a div supposed to be a box:

.newsBox{
  width: 100%;
  text-align: center;
  border-style: solid;
  border-width: medium;
  padding-left: 10px;
  padding-right: 10px;
  border-radius: 25px;
}

I am using this code in a PWA, and so it is going to be used on a mobile screen.

Instead of my div just spanning the entire screen of my phone, it spans off the screen as well (and so I have to move the screen left and right to view the whole box), but I can't understand why when my width is set to 100%. I have tried everything I could find on stack overflow and other websites; I think it may just be my code that's wrong.

Any help is appreciated. Thanks

Upvotes: 0

Views: 829

Answers (3)

M074554N
M074554N

Reputation: 71

After setting the the width to 100% and adding extra padding, it will show annoying scrollbars. Try to add the box-sizing: border-box; property to your div and it will be fixed.

Upvotes: 0

Deykun
Deykun

Reputation: 1270

The scroll probably appear because there is margin or padding property set up somewhere (browsers add them to html and body by default). You can turn it off with:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}  

box-sizing changes the way browser calculate the width of the element ( 100% - padding of the parent is used instead of 100%).

But it is hard to guess without an actual code.

Upvotes: 0

Ismael Padilla
Ismael Padilla

Reputation: 5566

Without the box-sizing property, an element with padding will actually be bigger than its width and height. You should try the following:

.newsBox{
    width: 100%;
    text-align: center;
    border-style: solid;
    border-width: medium;
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 25px;
    box-sizing: border-box;
}

You can read more about box sizing here.

Aditionally you must take into account the width of your newsBox's parent container. Setting newsBox's width to 100% means it will be full width within its parent.

Upvotes: 0

Related Questions