I’m new to HTML & CSS. I have a div called frame
inside the body of my webpage. Since the default position of frame
is in the top left corner, when I change the width & height properties, frame
extends to the right and bottom of the web page. Instead, I would like to see a border all the way around frame
instead of just across the top, and down the left side. I’ve included my HTML & CSS below.
body{
background-color: #006487;
}
.frame{
height: 100%;
width: 100%;
background-color: white;
margin: 10px;
position: absolute;
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
<title>Document</title>
</head>
<body>
<div class="frame">
</div>
</body>
</html>
My first attempt to scale back the frame
div was to set the height
& width
properties of frame
in px. This idea "works", but doesn’t scale to different size monitors. The next thing I tried was adding margin: 10px;
to the frame div, but this didn’t format frame
as I expected.
3
Answers
The
.frame
element is offset by a margin, but is also 100% of the width and height of its parent (thebody
). So it’s wider and taller than the window.You can make it smaller by using
calc()
in CSS. For example:(Note: I arrived at the value of
36px
because my browser adds an8px
margin tobody
plus your10px
margin on.frame
, doubled to account for each side. You’ll probably want to explicitly control the margin onbody
in case other users have different styling.)There are two ways of doing this:
calc
function to subtract 20px from the viewport height (top and bottom padding)box-sizing: border-box;
With both options you will need to remove the default margin and padding (for cross-browser consistency) that browsers will automatically set on HTML elements:
* { margin: 0; padding: 0; }
The * selector will select all elements, place this at the top of your CSS file. All other styles that follow it will overwrite this setting.
I am not sure why you have used absolute, but the result you needed can be done simply without using absolute positioning, please have a look at the code snippet below