Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep same width even if icon is hidden

Tags:

html

css

flexbox

I have a <div> and when it is hovered I am displaying a child <div> that contains an icon.

Because the icon is higher than the text, the new icon changes the parent <div>'s height. It also changes the <div>'s width because it is inserted at the end.

My question: I would like the <div> to hide the icon (with display:none) but still have the same size as if the icon was there (without using static width/height). So when the user hovers over the <div>, the icon will be displayed but the <div> sizes will stay the same.

Is that possible?

.container {
  display: flex;
}

.row {
  border: 1px solid black;
  cursor: pointer;
  display: flex;
}

.row:hover .icon {
  display: flex;
}

.icon {
  display: none;
}
<div class="container">
  <div class="row">
    <div class="text">This is my div. When it is hovered, I dont want it to change width and height because of the icon.</div>
    <div class="icon"><img src="http://i.imgur.com/NpIpU3F.png"></div>
  </div>
</div>

View on CodePen

like image 860
David Somekh Avatar asked Dec 05 '25 09:12

David Somekh


2 Answers

Use visibility: hidden instead of display: none

visibility: hidden preserves the space that elements occupy while making them invisibe. display: none removes elements from the flow of the page.

like image 173
McHat Avatar answered Dec 07 '25 21:12

McHat


use visibility: hidden; and visibility: visible;

display: none

Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off.

visibility: hidden

The element box is invisible (not drawn), but still affects layout as normal. Descendants of the element will be visible if they have visibility set to visible. The element cannot receive focus (such as when navigating through tab indexes).

Also move display: flex; to .icon if you still need it (or remove it since flex will stretch the image if your text warps to 2nd line).

.container {
  display: flex;
}

.row {
  border: 1px solid black;
  cursor: pointer;
  display: flex;
}

.row:hover .icon {
  visibility: visible;
}

.icon {
  visibility: hidden;
  display:flex;
}
<div class="container">
  <div class="row">
    <div class="text">This is my div. When it is hovered, I dont want it to change width and height because of the icon.</div>
    <div class="icon"><img src="http://i.imgur.com/NpIpU3F.png"></div>
  </div>
</div>
like image 37
Dalin Huang Avatar answered Dec 07 '25 23:12

Dalin Huang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!