Derek Story
Derek Story

Reputation: 9583

How to set equal height and width based on dynamic text using CSS only

Using CSS only, if you <div>Some dynamic text</div>, how do you make the height and width of the div equal dimensions when the width is determined by the dynamic text?

Upvotes: 0

Views: 1209

Answers (2)

Derek Story
Derek Story

Reputation: 9583

Similar to setting equal height based on the known width as answered here: https://stackoverflow.com/a/6615994/2479962

You first contain the dynamic text within a container and add a margin pusher (in this case :before) above the dynamic text element:

JS fiddle

<div class="container">
    <div class="element">
       Dimensions set by content.
    </div>
</div>

The trick is to base .element:before's margin off the dynamic contents font-size and padding:

CSS Only:

.container {
    display: inline-block;
    position: relative;
    background-color: silver;
}
.element {
    font-size: 20px;
    padding: 10px;
    /* So we don't have to take line-height into consideration during calc() */
    line-height: 1; 
}
.element:before {
    content: '';
    display: block;
    /*  100% is for 1:1 aspect ratio */
    /* 20px is taking the contents font-size plus the padding on each side */
    margin-top: calc(100% - 20px);
}

With @Rounin's suggestion, we can vertically center it using both :before and :after and dividing the calculations by two:

JS Fiddle - Vertically centered

.element:before, .element:after {
  content: '';
  display: block;
  /*  100% is for 1:1 aspect ratio */
  /* 10px is taking the contents font-size plus the padding on each side/2 */
  margin-top: calc(50% - 10px);
}

Upvotes: 2

Rounin
Rounin

Reputation: 29463

You can place a single paragraph element inside a div and give the p a margin using calc() which takes into account the width of the div (because % is always based on the width of the parent element).

Working Example:

div {
display: inline-block;
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
padding: 6px;
}

p {
margin: calc(50% - 12px) 0; /* half the width minus half the line-height */
font-size: 18px;
line-height: 24px;
}
<div>
<p contenteditable="true">Click me &amp; edit to change div size.</p>
</div>

Upvotes: 2

Related Questions