Luca Detomi
Luca Detomi

Reputation: 5716

textarea fit parents width minus margins

I'm sure that is a very common question but I am unable to find my simple situation in previous answers....

I have a textarea inside a div

Imagine that div has a width of 90% of its container and I would like that textarea spans across the entire width of div .notes minus a left, right margin of 10px

Something like 100% of div - 10px of left margin 10px of right margin")

<div class="notes">
  <h2>Title</h2>
  <textarea></textarea>
  <button>Save</button>
</div>

Obviously the solution could be very useful also for every other div inside a div for which we want to set a width in a similar way.... How to obtain this?

Upvotes: 3

Views: 300

Answers (2)

G-Cyrillus
G-Cyrillus

Reputation: 105903

you can use as well box-sizing and a padding instead a margin:

div {
  width:90%;
  margin:auto;
  padding:10px;
  box-sizing:border-box;/*includes border & padding */
  background:gray;
}
textarea {
  display:block;
  width:100%;
  box-sizing:border-box;/*includes border & padding */
}

DEMO http://codepen.io/anon/pen/uegjo

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157334

You can achieve that by using calc()

textarea {
    width: calc(100% - 20px); /* 20px = 10px for left and 10px for right */
    margin: auto; /* To horizontally center your textarea */
    display: block; /* Required for horizontally centering as well*/
}

Demo


Note: If you are conscious about the legacy browsers, make sure you use -webkit-calc and -moz-calc as well.

There are some js polyfills, like:

Upvotes: 5

Related Questions