I'm working on a portfolio design that consists of divs with backgrounds that repeat-x across the screen. I also want the contents of the divs to remain centered within a fixed width. Is there a way to do this better than having every div with background repeat-x and then a nested div with width:xxx and margin: 0 auto?

3 answers

1
point

I'm pretty sure that your suggestion is the only reasonable solution here.

Answered over 6 years ago by Joshua Clanton
  • Dang, I'm gonna need loads of nested divs =( Robert over 6 years ago
1
point

I don't see the point in your comment, that it somehow should be a problem that you have a lot of nested div's. Use CSS nesting to assign the margin property a bit more smart, if you're worried that it'll become a lot of CSS.
Consider this:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #container {text-align:center;margin:0 auto;width:800px;background:red;}
        #container div {margin:0 auto;width:50%;}
    </style>
</head>
<body>
    <div id="container">
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
        <div>Hello</div>
    </div>
</body>
</html>

You can easily add some background with repeat-x to #container; shouldn't be a problem. It's visible through the nested div's.
AND, works perfectly in all the browsers ...

Answered over 6 years ago by Sune Rasmussen
0
points

Hi! There is still hope to achieve the design you want without "double divs"!

But I have a question for you: do the larger DIV has a fixed width?

FOR FIXED WIDTH of the CONTAINER:

<!DOCTYPE html>
    <html>
    <head>
    <style type="text/css">
    p
    {
    background-image:url('gradient2.png');
    background-repeat:repeat-x;

    padding-left:100px;
    padding-right:100px;
    }
    </style>
    </head>

    <body>
    <p>Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!</p>
    </body>
</html>

...which you can try in Tryit Editor

And for Variable Width, you could use Javascript, to set the padding (both left and right) to:

(container_width-content_width)/2
Answered over 6 years ago by Dario Cangialosi