Paul Wicks
Paul Wicks

Reputation: 65540

How do I make a div expand to the width of the page with css?

I have a page with a couple of divs, sort of like this:

<div id="div_one">blah blah blah</div>
<div id="div_two">blah blah blah</div>

I want them to be centered horizontally, one after the other and for the second to expand to the width of the page.

Upvotes: 3

Views: 6089

Answers (4)

maksim
maksim

Reputation: 836

.first_one
{
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

.second_one
{
  width: 100%;
}

Then in your view, for the first one you would do

<div class = "first_one">
...
</div>

For the second, you would do

<div class = "first_one second_one">
...
</div>

Upvotes: 3

Kappers
Kappers

Reputation: 1331

body{ text-align: center; }

.first_one
{
  width: 600px; /* Can be any width */
  margin:0 auto;
}

/* Reset text-align for child content */
.first_one, .second_one{text-align: left}

In order to center "first_one" in IE6, you'll want to set 'text-align: center' on the parent element. In this case, I am assuming this is the body node. Also, margin: 0 auto does not work unless you specify a width.

You'll then want to set text-align left on the child divs so that the content within them is not centered.

You do not need to specify a width on "second_one" since block elements naturally expand to fill their parent containers. Additionally, by not setting the width, the browser will account for any padding, margin, and borders you may apply to "second_one" without breaking the layout.

Upvotes: 0

womp
womp

Reputation: 116977

Div's are the entire width of their container by default.

To center the contents horizontally, set "text-align: center;" on them. If they are in a container, also use "margin: auto" on the container, which will set the left and right margins to automatically center the div.

Upvotes: 0

Nick
Nick

Reputation: 9183

Keep in mind there are default margins on elements so it even though it's a 100% there could still be some gaps on the side. You can use some CSS to reset margins to 0 where needed.

Upvotes: 0

Related Questions