mrt181
mrt181

Reputation: 5316

How can I make a border with CSS around some elements without specifing an absolute width?

I am new to CSS and would like to draw a border around this:

fieldset {
  background-color: #e1e1e1;
  border: 1px solid #808080;
}

legend {
  background-color: #e1e1e1;
  border: 1px solid #808080;
  border-left-width;
  50%;
  color: #0667ad;
  font-style: italic;
  font-weight: bold;
}

div.menu {
  border: 1px solid #808080;
  padding: 1px;
  width: 271px;
}

p {
  margin: 1px;
}

label {
  border: 1px solid #e1e1e1;
  background-color: #84b0d4;
  color: #ffffff;
  display: block;
  float: left;
  margin-right: 1px;
  padding: 1px;
  text-align: right;
  width: 8em;
}

input {
  background: #ffffff;
  border: 1px solid #e1e1e1;
}
<form name="SomeForm" method="post" action="SomeAction">
  <fieldset>
    <legend>Details</legend>
    <div class="menu">
      <p><label for="UserName">Username</label><input name="UserName" id="UserName" type="text" value="#data[1].username#"></p>
      <p><label for="Password">Password</label><input name="Password" id="Password" type="password" value="#data[1].password#"></p>
      <p><label for="FirstName">First name</label><input name="FirstName" id="FirstName" type="text" value="#data[1].firstname#"></p>
      <p><label for="LastName">Last name</label><input name="LastName" id="LastName" type="text" value="#data[1].lastname#"></p>
    </div>
  </fieldset>
</form>

Right now I have defined the div width as 271px. Is there a way to wrap the border around the elements it contains without specifing an absolute width?

Upvotes: 0

Views: 6491

Answers (2)

David Hedlund
David Hedlund

Reputation: 129792

div.menu {
  border: 1px solid #808080;
  padding: 1px;
  float: left;
}

and

<div class="menu">
  <p><label for="UserName">Username</label><input name="UserName" id="UserName" type="text" value="#data[1].username#"></p>
  <p><label for="Password">Password</label><input name="Password" id="Password" type="password" value="#data[1].password#"></p>
  <p><label for="FirstName">First name</label><input name="FirstName" id="FirstName" type="text" value="#data[1].firstname#"></p>
  <p><label for="LastName">Last name</label><input name="LastName" id="LastName" type="text" value="#data[1].lastname#"></p>
</div>
<div style="clear: both;"></div>

Upvotes: 3

Rudism
Rudism

Reputation: 1655

Remove float: left from your labels, add float: left to your div.menu, and remove the width: 271px from your div.menu.

The reason it breaks now when you remove the width from div.menu is because the labels are floated left and not clearing the input above them.

Edit: Another option if you want to leave the labels floated left would be to add a clearing rule to the paragraphs within the menu:

div.menu p { clear: both; }

Upvotes: 1

Related Questions