简体   繁体   中英

Question on CSS width:100%

I want to create a flexible grid layout (ie no pixel value to be used anywhere) Now here is my question; For the outer container, generally I use

#container{width:1024px;margin:0 auto}

This is to center align the entire page. Now when I convert the same to a % based CSS ie

#container{width:100%;margin:0 auto}

In this case, the page does not center align. How do I fix this issue?

Page can't align centrally because it uses full browser width. try for example: "width:80%", and you'll see what i am talking about;

是的,当你填满整个宽度时,你怎么能期望某些东西在中心对齐。

You container does center align. Width of 100% means that the container occupies all width of parent container (let's assume screen), thus space for margins is 0 . Generally such problems are easily tracked with applying border to containers.

You can fix this issue by centering elements inside your container with text-align: center;

If I'm understanding the question correctly, you seem to be needing something to stop the container from widening infinitely, but still have it expand flexibly when the viewport is narrow. If this is the case, you can apply a max-width on it to tell it when to stop expanding:

#container {
    width: 100%;
    max-width: 1024px;
    margin: 0 auto;
}

In this case, your container will be flexible and take up all available width if the viewport is less than 1024 pixels wide, but won't go beyond 1024 pixels (and will be center-aligned) if the window grows wider.

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