I have a MUI Avatar element on my page:
<Avatar
sx={{ width: 180, height: "auto", maxHeight: 180, margin: 2 }}
variant="square"
alt={""}
src={
global.config.baseUrl +
"/image/logo" +
this.state.user.userId +
".jpg"
}
/>
this generates the following DOM:
<div class="MuiAvatar-root MuiAvatar-square css-eqjmj4">
<img alt="" src="/image/logo1.jpg" class="MuiAvatar-img css-1hy9t21">
</div>
with the following css class:
.css-eqjmj4 {
position: relative;
display: flex;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: center;
justify-content: center;
flex-shrink: 0;
height: 40px;
font-family: Roboto, Helvetica, Arial, sans-serif;
font-size: 1.25rem;
line-height: 1;
border-radius: 0px;
overflow: hidden;
user-select: none;
width: 180px;
max-height: 180px;
margin: 16px;
}
I want the width set to exactly 180px, with the height to scale proportionately (up to a maxHeight
of 180px
)
For some reason the css class hard-codes the height to height: 40px;
How can I override that?
2
Seems like the square
variant of the Avatar
is just CSS of height
and width
behind the scene, which isn’t exactly very intuitive.
My suggestion is to — add the style of aspect-ratio
(which is supported by all the modern browsers) yourself with the value of 1 / 1
so the code will look like this.
<Avatar
sx={{
width: 180,
aspectRatio: "1 / 1", // <-- look here
height: "auto",
maxHeight: 180,
margin: 2,
}}
variant="square" // doesn't matter anymore, can omit
src="/static/images/avatar/3.jpg"
/>
This will work with max-height
when you set the width
that is larger than it.
Heres a working example