Why does the box come out like this (padding/border/margin)?

174 views Asked by At

So this is my first day learning HTML&CSS and I'm currently having a problem. Why does this block come out like this (on left is what I get & on right is what I'm trying to achieve):

enter image description here

HTML:

    <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Temporary</title>
<link rel="stylesheet" href="main2.css">
</head>
<body id="top">

<code id="boxone">Welcome! <br>Dashed border</div>

</body>
</html>

CSS:

code {
background: #5CC7FF;
font-family: "Comic Sans MS", cursive, sans-serif;
padding: 2px;
margin-top: 1px;
margin-left: 1px;
margin-bottom: 4px;
margin-right: 4px;
text-align: center;
}

#boxone {
border: 8px dashed #5CA8FF;
}

The problem is that I want it to come out as a blue dashed box, but instead it comes out as two messed-up boxes.

2

There are 2 answers

1
Ana On BEST ANSWER

By default, <code> elements have a display of inline (which is going to generate an element box for every one of the parts separated by <br>).

Switching to display: block (code { display: block } in your CSS) or display: inline-block will mean creating just one element box for your <code>.

code {
  display: block;
  background: #5CC7FF;
  font-family: "Comic Sans MS", cursive, sans-serif;
  padding: 2px;
  margin: 1px 4px 4px 1px;
  text-align: center;
}

#boxone {
  border: 8px dashed #5CA8FF;
}

code:nth-child(2) { display: inline-block; }
<code id="boxone">Welcome! <br>Dashed border</code>
<code id="boxone">Welcome! <br>Dashed border</code>

0
puzzler On

Add display:block; to your code css. Also fix this line:

<code id="boxone">Welcome! <br>Dashed border</div>      <= </code>

Here is a fiddle: https://jsfiddle.net/rdgdz07o/ Use it for testing stuff out.