我正在尝试创建可重复用于不同内容的叠加弹出窗口,例如关于我们、联系我们、登录...
这是基本的 html:
<div class="overlays__map-overlay">
<div class="map-overlay__block">
//content from AJAX calls goes into here
</div>
</div>
和CSS:
.overlays__map-overlay{
display: none;
z-index: 5;
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: rgba(0,0,0, 0.3);
}
.map-overlay__block{
margin-left:auto;
margin-right:auto;
text-align: center;
background-color: rgba(105,105,105, 0.9);
border-radius: 5px;
width: auto;
margin-top: 15%;
max-width: 90%;
}
我想要的是 .map-overlay__block
占用我放入其中的内容的宽度。例如,如果用户单击“关于我们”页面,那么我将放入 width: 90vw;
的容器中,但如果单击“登录”,则会执行 ajax 调用并返回容器宽度为 500 像素的登录页面 html .
$('.nav-link').on('click', function(e) {
e.preventDefault();
var actionUrl = $(this).attr('href');
$.getJSON(actionUrl, function(jsonResponse){
$('.overlays__map-overlay .map-overlay__block').html(jsonResponse.view);
$('.overlays__map-overlay').css('display', 'block');
});
});
问题是 map-overlay__block
总是占宽度的 90%!我尝试将 display
选项更改为 inline-block
。它确实占用了子元素的宽度(登录页面为 500px)但是 margin-left:auto; margin-right:auto;
规则停止以居中方式工作。
最佳答案
使用flex boxes
添加以下覆盖类
display: flex;
align-items: center;
工作示例:
function moreContent(){
document.querySelector('.map-overlay__block').innerHTML = "Echo park tumblr meggings, pabst glossier yuccie iceland street art sriracha sartorial vegan thundercats green juice. Cornhole pork belly 90's prism, portland ennui kitsch dreamcatcher retro tumblr austin. Echo park normcore skateboard banh mi, small batch synth air plant fashion axe gastropub fap flexitarian godard sriracha blue bottle green juice. Cred mumblecore kale chips tumblr, pitchfork bushwick green juice fingerstache health goth truffaut XOXO cronut. Jianbing disrupt 3 wolf moon farm-to-table food truck. Meditation mumblecore post-ironic gastropub man braid. Af paleo franzen, la croix banjo man bun lumbersexual cold-pressed lyft mlkshk artisan.";
}
.overlays__map-overlay{
//display: none;
z-index: 5;
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: rgba(0,0,0, 0.3);
display: flex;
align-items: center;
}
.map-overlay__block{
margin-left:auto;
margin-right:auto;
text-align: center;
background-color: rgba(105,105,105, 0.9);
border-radius: 5px;
width: auto;
max-width: 90%;
}
button {
position: relative;
z-index: 100
}
<div class="overlays__map-overlay">
<div class="map-overlay__block">
//content from AJAX calls goes into here
</div>
</div>
<button onclick="moreContent()">More Content</button>
关于html - 如何使父 div 占用子宽度并水平居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41987076/