css 中心元素的内容在溢出时被截断[重复]

46qrfjad  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(102)

此问题已在此处有答案

Can't scroll to top of flex item that is overflowing container(12个回答)
昨天关门了。
我有一个元素,我需要在两个轴上的页面中心。我尝试使用flexbox来实现这一点,但是,当元素的容器溢出时(例如:例如,浏览器窗口太小,无法容纳整个元素),元素的内容从左侧和顶部被截断,无法滚动并查看整个内容:

body {
  margin: 30px;
}

.resizer {
  
  border: 1px dashed black;
  resize: both;
  
  width: 400px;
  height: 400px;
  overflow: auto;
  
  display: flex;
  align-items: center;
  justify-content: center;
  
  background-color: #888;
  
}

.centered {
  flex: 0 0 300px;
  background-color: lime;
}
<div class="resizer">
  <div class="centered">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in imperdiet justo, a porttitor lectus. Suspendisse vel tempor arcu, a pretium lectus. Ut et magna vitae purus porta egestas at ut elit. Nulla faucibus nibh sed purus pulvinar, in dictum est vestibulum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec varius placerat dolor, non commodo purus malesuada eget. Fusce congue non erat ullamcorper ultricies. Fusce sed tellus lectus. Aenean quis maximus augue, eu placerat urna.
  </div>
</div>

看起来浏览器只在一个方向(右下角)计算溢出。
是否有可能使整个内容在溢出时可访问而不使用媒体查询?

omqzjyyz

omqzjyyz1#

看起来CSS Grid更适合这种布局目的。
只需为父容器设置以下属性:

.container {
  display: grid;
  align-items: center;
  justify-items: center;
}

它应该正确工作:

body {
  margin: 30px;
}

.resizer {
  
  border: 1px dashed black;
  resize: both;
  
  width: 400px;
  height: 400px;
  overflow: auto;
  
  display: grid;
  align-items: center;
  justify-items: center;
  
  background-color: #888;
  
}

.centered {
  width: 300px;
  background-color: lime;
}
<div class="resizer">
  <div class="centered">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in imperdiet justo, a porttitor lectus. Suspendisse vel tempor arcu, a pretium lectus. Ut et magna vitae purus porta egestas at ut elit. Nulla faucibus nibh sed purus pulvinar, in dictum est vestibulum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec varius placerat dolor, non commodo purus malesuada eget. Fusce congue non erat ullamcorper ultricies. Fusce sed tellus lectus. Aenean quis maximus augue, eu placerat urna.
  </div>
</div>

相关问题