Home > Enterprise >  Change img via css if it is out the container
Change img via css if it is out the container

Time:02-11

I've got a container for image and img inside.

Is there some way to change the img content if it's width becomes bigger than the container width via css? Maby image-set?

nav{; 
    width: 100%;
    padding: 0;
    height:70px;
    display: flex;
    position: relative;
    border-bottom: 1px solid #b8bbc0;
}

.logo-container{  
    display: inline-block;
    overflow: hidden;
    max-width: 25%;
    flex: 0 0  25%;
    -ms-flex: 0 0  25%;
    padding: 5px 0;
    margin: 5px 5px 5px 0;
    position: absolute;
    left: 5px;
}
.logo-helper{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.logo-container img{
    max-height:40px;
    margin: 5px;  
    display: inline-block;
    content:   url(https://wilcity.com/wp-content/uploads/2018/12/sample-logo-design-png-3.png);
}
    <nav>
    <div >
        <span ></span>
        <img>
    </div>
    </nav>

CodePudding user response:

You cannot conditionally set any property in CSS because it is not a programming language. You can do this in JavaScript.

var img = document.getElementById("my-img");
var container = document.getElementById("image-container");
if(img.style.width > container.style.width){
 img.src = "http://example.com/myimg.png"

}

CodePudding user response:

It is a little tricky to change your code since you for some reason decided to use the content - it is normally used for pseudo elements.

Here I use just src instead

const img = new Image()
img.addEventListener("load",function() {
  const w = this.width, h=this.height;
  const container = document.querySelector(".logo-container");
  const style = window.getComputedStyle(container)
  const sW = parseFloat(style.width)
  const img = container.querySelector("img")
  console.log(w,sW)
  if (w > sW) this.src='https://via.placeholder.com/150?text=150px'
  img.src=this.src
})

img.src="https://wilcity.com/wp-content/uploads/2018/12/sample-logo-design-png-3.png"
nav {
  ;
  width: 100%;
  padding: 0;
  height: 70px;
  display: flex;
  position: relative;
  border-bottom: 1px solid #b8bbc0;
}

.logo-container {
  display: inline-block;
  overflow: hidden;
  width: 25%;
  max-width: 25%;
  flex: 0 0 25%;
  -ms-flex: 0 0 25%;
  padding: 5px 0;
  margin: 5px 5px 5px 0;
  position: absolute;
  left: 5px;
  border: 1px solid black;
}

.logo-helper {
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.logo-container img {
  max-height: 40px;
  margin: 5px;
  display: inline-block;
}
<nav>
  <div >
    <span ></span>
    <img>
  </div>
</nav>

  • Related