简体   繁体   中英

Make inner div 100% width of body

I want the child div width to be 100% of the body.

CSS

#container {
    position:relative;
    width:400px;
    height:100px;
    margin:0 auto;
    background:red;
}
#inner {
    width:100%;
    height:30px;
    background:blue;
}

HTML

<div id="container">
    <div id="inner"></div>
</div>

Here is the fiddle

I'm using position:relative for parent div and the position:absolute; solution is not working. How can I do this? Js solutions are acceptable.

Check this fiddle

CSS

body {
    margin-top:30px;
}
#container {
    width:400px;
    height:100px;
    margin:0 auto;
    background:red;
}
#inner {
    width:100%;
    height:20px;
    background:blue;
    position:absolute;
    right:0;
    left:0;
}

You just have to remove the position:relative from the container div and everything will work as expected

AND

I dont think there is a need for writing JS for this as this can be just obtained using CSS.

In html, if you have an element inside of a container while using % it will respect the containers boundaries.

So, no sure why Lal was downvoted. but his solution works.

Especially because your container is relative, the absolute container will be absolute to the container and not the body itself. You could remove position: relative; on the container and it will work that way, but it depends on what you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM