Hi all
I have a codepen here -
https://codepen.io/mt-ttmt/pen/WJpjoN
Its really simple and basic, its the basic structure I’m working with.
Basically I have a div inside a container, the div inside the container needs to have 100% width.
I wanted to have a margin on each side of this div.
If I do this the div gets pushed out of its container.
Is there a way to have the div with 100% and margins each side.
The easy way is just to remove the float and the width, then let 50px side margins take care of it.
.content{
background: red;
min-height: 50px;
margin: 0 50px;
Another way (unnecessary in this case) is to use calc
.content{
background: red;
min-height: 50px;
width: calc(100% - 100px);
margin: 0 auto;
And if for some strange reason it actually needed to be a dimensioned float then calc could do that too.
.content{
background: red;
min-height: 50px;
width: calc(100% - 100px);
float: left;
margin-left:50px;
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">
<title>untitled document</title>
<link rel="stylesheet" href="screen.css" media="screen">
<style media="screen">
body {
background-color: #d3d3d3;
font: 100% / 162% verdana, arial, helvetica, sans-serif;
.page{
width: 80%;
padding: 1em 3em;
margin: 0 auto;
box-sizing: border-box;
background-color: #fff;
.content {
padding: 1em;
background-color: #f00;
</style>
</head>
<div class="page">
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Curabitur sit amet sem sed libero bibendum tempus faucibus
quis mi. Nulla rhoncus vel ipsum in volutpat. Nam tortor
nibh, posuere ac lorem ut, suscipit tincidunt leo. Duis
interdum justo ac justo vehicula consequat. Curabitur et
volutpat nibh. Phasellus rutrum lacus at dolor placerat
feugiat. Morbi porta, sapien nec molestie molestie, odio
magna vestibulum lorem, vitae feugiat est leo sit amet nunc.
</body>
</html>
coothead
The best way is to not add unnecessary css that breaks the natural behaviour of block elements.
Block elements will by default have a width
value of auto
which is more useful than width: 100%
because it will naturally fill the width of its container taking into account any margins and borders.
When you have width: 100%
and a 50px
margin, the width the element takes up is 100% + 100px (50px each side) which will exceed 100% and thus overflow the container.
The float is another unnecessary complication, that would generally be used only on smaller elements when specifically required by a layout.
Simply removing the width
and float
rules from .content
will fix the issue.