Power-Up Games
Power-Up Games

Reputation: 13

CSS div tags not the size of parent when using percents

I am trying to make the div tags in my HTML a percent of the size of the parent div, without being too small or too large. What I get when I check the size of the div with this code:

#main {
    width: 800px;
    height: 800px;
    margin: 0 auto;
}

.sidebar {
    width: 31%;
    margin-right: 1%;
    margin-left: 2%;
}

.content {
    width: 61%;
    margin-right: 2%;
    margin-left: 1%;
}

.sidebar, .content {
    background: #888;
    height: 100%;
    float: left;
    border-radius: 4px;
    color: #FFF;
    font-family: Helvetica;
    text-align: center;
}

.sidebar_inner, .content_inner {
    height: 100%;
    width: 100%;
    padding: 0%;
    font-size: 1em;
    background-color: black;
}
<div id="main">
    <div class="sidebar">
        <div class="sidebar_inner">
            <h1>Hello!</h1>
        </div>
    </div>
    <div class="content">
        <div class="content_inner">
            <h1>Hello again!</h1>
        </div>
    </div>
</div>

result

The blue box is the inner div tag. Here is a better picture of the problem

enter image description here

Upvotes: 1

Views: 104

Answers (4)

Alex
Alex

Reputation: 8695

The problem is h1 margin. Browsers have default style for line heights, margins and font sizes of headings, and so on. However, you can solve your problem by giving margin:0; to the h1 element or use css reset to solve your problem.

h1
{
   margin:0;
   padding:0;
}

#main {
    width: 800px;
    height: 800px;
    margin: 0 auto;
}

.sidebar {
    width: 31%;
    margin-right: 1%;
    margin-left: 2%;
}

.content {
    width: 61%;
    margin-right: 2%;
    margin-left: 1%;
}

.sidebar, .content {
    background: #888;
    height: 100%;
    float: left;
    border-radius: 4px;
    color: #FFF;
    font-family: Helvetica;
    text-align: center;
}

.sidebar_inner, .content_inner {
    height: 100%;
    width: 100%;
    padding: 0%;
    font-size: 1em;
    background-color: black;
}

h1
{
   margin:0;
   padding:0;
}
<div id="main">
    <div class="sidebar">
        <div class="sidebar_inner">
            <h1>Hello!</h1>
        </div>
    </div>
    <div class="content">
        <div class="content_inner">
            <h1>Hello again!</h1>
        </div>
    </div>
</div>

Upvotes: 0

Tamik Soziev
Tamik Soziev

Reputation: 14798

It's happening because you have a top margin on your H1 tag.

Upvotes: 0

Gabriel Cuenca
Gabriel Cuenca

Reputation: 121

All the properties of #main require a measurement unit...

#main {
width: 800px
height: 800px;
margin: 0px auto;
}

For you example, px is good.

Upvotes: 0

Huski
Huski

Reputation: 978

You will need to have units on your width and height such as px, em, rem, %, vh, vw.

Upvotes: 1

Related Questions