繁体   English   中英

我想将div中包含的图像居中。 当我将50%的保证金设置为最高时,它从div中流出。 我如何包含它?

[英]I want to center my image contained in a div. When i set 50% margin-top, it is flowing out of the div. How do i contain it?

这只是我的代码的片段。 如果设置了margin-top,我似乎无法将图像锁定在div内:50%的图像只是从div流出。 我该如何阻止呢? 我也想在包含它的div的死点处设置一个图像。

 var twitchArr = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; var dataArray; twitchArr.forEach(function(twitch) { $.getJSON('https://api.twitch.tv/kraken/streams/' + twitch + '?client_id=lgiuraoc2wbg635m7ewteblxg38n4b', function(data) { console.log(data.stream); /*just for checking*/ if (data.stream !== null) { forOnline(data.stream.channel.logo, data.stream.channel.game, data.stream.channel.status); function forOnline(img, gameName, description) { var para = '<div class="off">' + '<img id="mainImg" src=' + img + '>' + '</div>'; var para1 = '<div class="off1">' + '<p id="textovo">' + gameName + ": " + description + '</p>' + '</div>'; $(".imgFirst").append(para); $(".textSecond").append(para1); } } else { 
 #mainImg { border-radius: 100%; border: 0 solid white; width: 60%; height: 80%; position: relative; margin-top: 40px; } /*adjusting the image only*/ .off, .off1, .off2, .off3 { height: 6em; padding: 0 0 0 0; margin-top: 0em; margin-bottom: .3em; } .off { max-width: 99px; max-height: 83px; } 
 <div class='container-fluid' id=onlyForOnline> <div class="row"> <div class="col-xs-2 imgFirst removePadding"> </div> <div class="col-xs-10 textSecond removePadding"> </div> </div> </div> 

我对您的问题不太确定,但我认为去掉margin-top并添加object-fitobject-position可能会解决您的问题。

尝试以下CSS

.off{
   max-width: 99px;
   max-height: 83px;
   object-fit: contain;
   object-position: center;
}

#main-img删除margin-top

  1. 这是因为您的图片大于div高度的50%。
  2. 使用Calcmargin: calc((100% / 2) - 10px); 其中10px是图片宽度的一半。

 div{ display: block; width: 200px; //For testing height: 200px; //For testing background-color:grey; //For testing } #mainImg { margin: calc((100% / 2) - 10px); width: 20px; //For testing height: 20px; //For testing } 
 <div> <img src="http://doesnotexist.com/img" id="mainImg"> </div> 

我以前没用过css类。 请参考。

.valign-middle {position: relative; float: left; display: inline-block; width: 100%; text-align: center; top: 50%; left: 50%; transform: translate(-50%, -50%);}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM